How do I generate Angular route configurations dyn

2019-06-06 13:15发布

问题:

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