How do I generate Angular route configurations dynamically/pragmatically?

寵の児 提交于 2019-12-08 06:09:36

问题


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'}]
    }
}

The routing component,

@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()
    }
}

Is there any method like *ngFor that can be used to loop through pages inside the RouteConfig decorator?

I want to get the route configurations as,

something like,

{path: '/{{page.slug}}', name: '{{page.name}}', component: PersonComponent}

thanks


回答1:


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);
    }
}

Here's a plnkr with the example working



来源:https://stackoverflow.com/questions/35991639/how-do-i-generate-angular-route-configurations-dynamically-pragmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!