不允许通过字符串文字访问对象!当我尝试通过动态ID访问(route.params['id']路由参数时



这是我的[app-routing.modulse.ts]模块

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 {
}

这是子组件配方详细信息组件! 并在尝试访问路由参数 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) => {
            // error lies below
            this.id = +params['id'];
            this.recipe = this.recipeService.getRecipe(this.id);
        });
    }
}

我收到一条错误消息"不允许通过字符串文本访问对象"尝试访问动态路由参数 ID 时

你能试试这个吗?

route.params.subscribe((params: {id: string}) => {
  this.id = +params.id;
})

**我正在根据评论修改它

只需将应用程序路由更新为

const appRoutes: Routes = [
 { path: 'recipes', component: RecipesComponent, children: [
 { path: ':id', component: RecipeDetailComponent },
 { path: '', component: RecipeStartComponent },
  ] }, //add the rest......

最新更新