[英]angular2 router interpreting route as parameter?
我正在嘗試使用路由參數路由到子模塊,我的app.routes看起來像
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:無法讀取未定義的屬性“ length”
這似乎是因為使用了未定義的路由,如果我只調用/cell
那么我的組件會正常加載並將cell
打印到控制台。 路由器為什么將路由解釋為參數?
使用以下代碼獲取ID:
import { ActivatedRoute, Router } from '@angular/router';
constructor(public route: ActivatedRoute, ...) {
}
ngOnInit() {
this.route
.params
.subscribe(params => {
this.id= params['id'];
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.