如何生成 Angular 路由配置 dynamically/pragmatically?
How do I generate Angular route configurations dynamically/pragmatically?
您好,我正在尝试实用地定义 Angular 2 条路线路径。
我有一个服务 returns 路径,所有路径都使用通用组件进行路由
服务如下图,(所有路径都是动态生成的)
export class PagesService{
getPages() :string[] {
return [{"slug": 'john',"name": 'John'},{"slug": 'martin',"name": 'Martin'},{"slug": 'alex',"name": 'Alex'},{"slug": 'susan',"name": 'Susan'}]
}
}
路由组件,
@Component({
selector : 'app',
template : `
<router-outlet></router-outlet>
`,
directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
{path: '/', name: 'Home', component: HomeComponent}
])
export class RouteComponent{
constructor(private _pageService: PagesService){
this.pages = this._pageService.getPages()
}
}
有没有像*ngFor
这样的方法可以用来在RouteConfig
装饰器中循环遍历pages
?
我想获取路由配置,
有点像,
{path: '/{{page.slug}}', name: '{{page.name}}', component: PersonComponent}
谢谢
如@toskv 所建议
您可以使用 Router#config 来完成此操作,它允许您动态配置路由。
使用您问题中的服务的超级简单片段
@Component({
// Generate de router links dynamically as well
template : `
<div *ngFor="#page of pages">
<a [routerLink]="[page.name]">
{{page.slug}}
</a>
</div>
`,
providers : [PagesService]
})
export class App {
pages = [];
constructor(public pgSvc: PagesService, router: Router) {
this.pages = pgSvc.getPages(); // cache the pages
let config = []; // Array to contain the dynamic routes
for(let i = 0; i < this.pages.length; i++) {
config.push({
path: this.pages[i].slug,
name : this.pages[i].name,
component: PersonComponent
});
}
// Configure the Router with the dynamic routes
router.config(config);
}
}
这是一个 plnkr 示例
您好,我正在尝试实用地定义 Angular 2 条路线路径。
我有一个服务 returns 路径,所有路径都使用通用组件进行路由
服务如下图,(所有路径都是动态生成的)
export class PagesService{
getPages() :string[] {
return [{"slug": 'john',"name": 'John'},{"slug": 'martin',"name": 'Martin'},{"slug": 'alex',"name": 'Alex'},{"slug": 'susan',"name": 'Susan'}]
}
}
路由组件,
@Component({
selector : 'app',
template : `
<router-outlet></router-outlet>
`,
directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
{path: '/', name: 'Home', component: HomeComponent}
])
export class RouteComponent{
constructor(private _pageService: PagesService){
this.pages = this._pageService.getPages()
}
}
有没有像*ngFor
这样的方法可以用来在RouteConfig
装饰器中循环遍历pages
?
我想获取路由配置,
有点像,
{path: '/{{page.slug}}', name: '{{page.name}}', component: PersonComponent}
谢谢
如@toskv 所建议
您可以使用 Router#config 来完成此操作,它允许您动态配置路由。
使用您问题中的服务的超级简单片段
@Component({
// Generate de router links dynamically as well
template : `
<div *ngFor="#page of pages">
<a [routerLink]="[page.name]">
{{page.slug}}
</a>
</div>
`,
providers : [PagesService]
})
export class App {
pages = [];
constructor(public pgSvc: PagesService, router: Router) {
this.pages = pgSvc.getPages(); // cache the pages
let config = []; // Array to contain the dynamic routes
for(let i = 0; i < this.pages.length; i++) {
config.push({
path: this.pages[i].slug,
name : this.pages[i].name,
component: PersonComponent
});
}
// Configure the Router with the dynamic routes
router.config(config);
}
}
这是一个 plnkr 示例