angular2路由器将路由解释为参数?
问题描述:
我想路由到一个子模块,路由参数,可以我app.routes看起来像angular2路由器将路由解释为参数?
import { Routes, RouterModule } from '@angular/router';
const appRoutes: Routes = [
{ path: 'cell', loadChildren: './cell/cell.module#CellModule', pathMatch: 'prefix'}
];
export const appRoutingProviders: any[] = [];
export const routing = RouterModule.forRoot(appRoutes);
我的孩子要素(小区)有以下途径:
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CellComponent } from './cell.component';
const cellRoutes: Routes = [
{ path: ':id', component: CellComponent, pathMatch: 'full' }
];
export const cellRouting: ModuleWithProviders = RouterModule.forChild(cellRoutes);
和CellComponent
看起来是这样的:
export class CellComponent implements OnInit {
@Input()
dep: string;
constructor(
private route: ActivatedRoute) { }
ngOnInit() {
this.route.params.forEach((params: Params) => {
this.dep = params['id'];
console.log(this.dep);
});
}
}
我希望能够调用/cell/2
路线,以米获得2
Ÿ控制台,但是,如果我打这通电话,我得到一个错误:
TypeError: Cannot read property 'length' of undefined
这似乎是因为使用了不确定的路线,如果我只是叫/cell
然后我的组件加载罚款,并打印cell
到安慰。为什么路由器将路由解释为参数?下面的代码
答
用于获取ID:
import { ActivatedRoute, Router } from '@angular/router';
constructor(public route: ActivatedRoute, ...) {
}
ngOnInit() {
this.route
.params
.subscribe(params => {
this.id= params['id'];
});
}
都能跟得上 - 这并不能帮助我很害怕。我相信这是一个路由问题,因为该组件在另一个项目中正常工作(我正在将此功能重构为导致此问题的新模块)。 –