Let's take a look at my custom [app-routing.modulse.ts] module:
const appRoutes: Routes = [
{ path: '', redirectTo: '/recipes', pathMatch: 'full' },
{ path: 'recipes', component: RecipesComponent, children: [
{ path: '', component: RecipeStartComponent },
{ path: ':id', component: RecipeDetailComponent },
] },
{ path: 'shopping-list', component: ShoppingListComponent },
];
@NgModule({
imports: [RouterModule.forRoot(appRoutes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
This snippet showcases the childComponent RecipeDetailsComponent which is causing an error when attempting to access the route parameter 'id':
import { Component, OnInit, Input } from '@angular/core';
import { Recipe } from '../recipe.model';
import { RecipeService } from '../recipe.service';
import { ActivatedRoute, Params, Router } from '@angular/router';
@Component({
selector: 'app-recipe-detail',
templateUrl: './recipe-details.component.html',
styleUrls: ['./recipe-details.component.css']
})
export class RecipeDetailComponent implements OnInit {
recipe: Recipe;
id: number;
constructor(private recipeService: RecipeService,
private route: ActivatedRoute,
private router: Router) {
}
ngOnInit() {
this.route.params.subscribe((params: Params) => {
// The error occurs here
this.id = +params['id'];
this.recipe = this.recipeService.getRecipe(this.id);
});
}
}
Encountering the error message "object access via string literals is disallowed" is a result of trying to retrieve the dynamic route parameter 'id'.