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?
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'];
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.