简体   繁体   中英

Angular 2 RC Final - Dynamically loading route data from service

I'm trying to load route data from a service and automatically generate routes in Angular 2 RC Final. I see that you can assign route data via the Router.Module.forRoot() function but don't see a way of assigning fetched data to the function. I tried the code below but get a "Property 'forRoot' does not exist on type 'RouterModule' error".

I may be completely off the mark, but the code should show roughly what I'm trying to achieve. The app paths are: mysite.com/london/ mysite.com/new-york/, etc. Is there a way of doing this?

The router version I am using is: "@angular/router": "~3.0.1"

app.module.ts:

import { NgModule, OnInit  } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { RouterModule } from '@angular/router';
import { PathService } from './path.service';
import { Path } from './path';

@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        RouterModule
    ],
    declarations: [
        AppComponent
      ],
    providers: [
        PathService
    ],
    bootstrap: [ AppComponent ]
})
export class AppModule implements OnInit {
    private ROUTES: Array<Object>;
    private paths: Path[];

    constructor(
        @Inject(RouterModule) private _routerModule: RouterModule,
        @Inject(PathService) private _pathService: PathService) {}

    ngOnInit() {
        this.getPathData();
    }

    getPathData() {
        this._pathService.getPaths().subscribe((paths: Path[]) => this.paths = paths, (err: any) => { }, () => this.generateRoutes());
    }

    generateRoutes() {
        this.ROUTES = 'do something to this.paths and assign route date here';

        this._routerModule.forRoot(this.ROUTES);
    }
}

JSON:

[
    {
        id: "1",
        name: "London",
        path: "london"
    },
    {
        id: "2",
        name: "New York",
        path: "new-york"
    },
    {
        id: "3",
        name: "Paris",
        path: "paris"
    },
    {
        id: "4",
        name: "Tokyo",
        path: "tokyo"
    }
]

not sure as this seems very cutting edge. The closest to what you want is lazy loading routes. Heres a very simple demo. The routes are loaded when they are first visited on demand.

I doubt it helps but worth a shot :)

https://github.com/danday74/angular2-router-modular/blob/master/app/app-routing.module.ts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM