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

时间:2019-03-25 15:11:33

标签: angular typescript

这是我的[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 {

}

这是childComponent RecipeDetailsComponent!并在尝试访问路由参数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

1 个答案:

答案 0 :(得分:0)

您可以尝试吗?

createJobRepository

**我正在根据评论进行修改

只需将appRoutes更新为

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