0

I am trying to route to a child module with route params, my app.routes looks like

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);

my child component (cell) has these routes:

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);

and CellComponent looks like this:

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);
    });

  }
}

I expect to be able to call the /cell/2 route and get 2 in my console, however, if I make that call, I get an error:

TypeError: Cannot read property 'length' of undefined

which seems to be because of using an undefined route, and if I just call /cell then my component loads fine and prints cell to the console. Why is the router interpreting the route as a parameter?

George Edwards
  • 8,017
  • 16
  • 64
  • 135

1 Answers1

0

Use below code to get the id:

import { ActivatedRoute, Router } from '@angular/router';
constructor(public route: ActivatedRoute, ...) {
}
ngOnInit() {
    this.route
        .params
        .subscribe(params => {
            this.id= params['id'];
    });
}
JS dev
  • 8,456
  • 12
  • 68
  • 111
  • Nope - that doesn't help I am afraid. I am confident this is a routing issue, as the component works fine in another project (I am refactoring this functionality into a new module which is what has caused the issue.) – George Edwards Dec 02 '16 at 19:18