【发布时间】:2016-11-04 10:08:08
【问题描述】:
我正在尝试从服务加载路由数据并在 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"
}
]
【问题讨论】:
-
我最终通过在路由模块中使用
path: ":city"解决了我自己的问题。这只会处理任何被扔向它的城市。
标签: javascript angular typescript angular2-routing