簡體   English   中英

angular2路由器將路由解釋為參數?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM