如何生成角路由配置动态/务实? [英] How do I generate Angular route configurations dynamically/pragmatically?
本文介绍了如何生成角路由配置动态/务实?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好我试图以务实的态度定义角度2路由路径。
Hi I am trying to define the Angular 2 route paths pragmatically.
我有一个返回的路径服务,所有路径使用共同的组件路由
I have a service that returns the paths, all the paths use a common component for routing
服务如下所示,(所有的路径是动态生成的)
the service is shown below, (all paths are generated dynamically)
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
可以通过页
的<$ C $内使用循环C> RouteConfig 装饰?
我想要得到的路由配置为,
I want to get the route configurations as,
类似,
{path: '/{{page.slug}}', name: '{{page.name}}', component: PersonComponent}
感谢
推荐答案
作为建议的@toskv
As suggested by @toskv
您可以通过使用路由器配置#它可以让你做到这一点动态配置路由。
You can accomplish this by using Router#config which lets you to configure routes dynamically.
在你的问题使用该服务的超级简单的代码片段
Super simple snippet using the service in your question
@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 使用实例的
这篇关于如何生成角路由配置动态/务实?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文