0

我正在尝试使用路由参数路由到子模块,我的 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:无法读取未定义的属性“长度”

这似乎是因为使用了未定义的路由,如果我只是调用,/cell那么我的组件会很好地加载并打印cell到控制台。为什么路由器将路由解释为参数?

4

1 回答 1

0

使用以下代码获取 id:

import { ActivatedRoute, Router } from '@angular/router';
constructor(public route: ActivatedRoute, ...) {
}
ngOnInit() {
    this.route
        .params
        .subscribe(params => {
            this.id= params['id'];
    });
}
于 2016-12-02T17:09:23.957 回答