如何从Angular 4中的路由中获取变量“数据”?

问题描述:

你能否举个例子来说明如何从路由中获取数据。 Routing & Navigation如何从Angular 4中的路由中获取变量“数据”?

const appRoutes: Routes = [ 
    { path: 'crisis-center', component: CrisisListComponent }, 
    { path: 'hero/:id',  component: HeroDetailComponent }, 
    { 
    path: 'heroes', 
    component: HeroListComponent, 
    data: { title: 'Heroes List' } // <--- How to use this data? 
    }, 
    { path: '', 
    redirectTo: '/heroes', 
    pathMatch: 'full' 
    }, 
    { path: '**', component: PageNotFoundComponent } 
]; 

谢谢

+0

在链接页面中有一段:第三条路线中的数据属性是存储与此特定路线相关的任意数据的地方。数据属性可在每条激活的路由中访问。用它来存储项目,如页面标题,面包屑文本和其他只读的静态数据。您将在后面的指南中使用解析警卫来检索动态数据。“ DV缺乏自我研究 –

您可以在组件/服务构造函数使用ActivatedRoute

例如:

public class MyAppComponent{ 
data: any; 

constructor(route: ActivatedRoute){ 
     this.data = route.snapshot.data; 
    } 
} 

你可以找到更多的细节here