不允许通过字符串文字访问对象!当我尝试通过动态 id 访问 (route.params['id'] 路由参数时
Posted
技术标签:
【中文标题】不允许通过字符串文字访问对象!当我尝试通过动态 id 访问 (route.params[\'id\'] 路由参数时【英文标题】:object access via string literals is disallowed ! while i try to access (route.params['id'] route param via dynamic id不允许通过字符串文字访问对象!当我尝试通过动态 id 访问 (route.params['id'] 路由参数时 【发布时间】:2019-08-15 21:04:55 【问题描述】:这是我的 [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 时
【问题讨论】:
How to rewrite code to avoid TSLint "object access via string literals"的可能重复 发帖前请search。更多关于搜索here。 我在发布代码之前有 serach。但我没有找到适合我的答案。无论如何谢谢你。 【参考方案1】:你能试试这个吗?
route.params.subscribe((params: id: string) =>
this.id = +params.id;
)
**我正在根据 cmets 修改这个
只需将 appRoutes 更新为
const appRoutes: Routes = [
path: 'recipes', component: RecipesComponent, children: [
path: ':id', component: RecipeDetailComponent ,
path: '', component: RecipeStartComponent ,
] , //add the rest......
【讨论】:
您能简要介绍一下您要达到的目标吗?您是否尝试从 route.params 获取值?以上是关于不允许通过字符串文字访问对象!当我尝试通过动态 id 访问 (route.params['id'] 路由参数时的主要内容,如果未能解决你的问题,请参考以下文章
在 TypeScript 中使用类型变量访问对象文字不起作用