Angular 2 RC Final - 从服务

时间:2016-11-04 10:08:08

标签: javascript angular typescript angular2-routing

我尝试从服务加载路由数据并在Angular 2 RC Final中自动生成路由。我看到你可以通过Router.Module.forRoot()函数分配路由数据,但是没有看到将获取的数据分配给函数的方法。我尝试了下面的代码,但获得了一个"属性' forRoot'在类型' RouterModule'上不存在错误"

我可能完全不合适,但代码应该大致显示我想要实现的目标。应用程序路径是:mysite.com/london/ mysite.com/new-york/等。有没有办法做到这一点?

我使用的路由器版本是:" @ 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"
    }
]

1 个答案:

答案 0 :(得分:0)

不确定,因为这似乎非常前沿。最接近你想要的是延迟加载路线。这是一个非常简单的演示。首次按需访问路线时会加载路线。

我怀疑它有帮助,但值得一试:)

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