【发布时间】:2022-01-05 16:16:09
【问题描述】:
我有两个组件:recipe 和 recipe-detail。 Recipe 正在显示我的数据库中的食谱列表,并且 recipe-detail 应该显示给定食谱的详细信息。我想要实现的是,每当有人点击配方名称时,我想将他路由到配方详细信息组件。 这是我的食谱 html:
<section class="columns">
<div class="column" *ngFor="let recipe of RecipeList">
<h2><a routerLink="recipes/{{recipe.Id}}" routerLinkActive="true">{{recipe.name}}</a></h2>
<p>{{recipe.recipeBody}}</p>
</div>
</section>
我的路由文件:
{path:'recipes', component: RecipeComponent},
{path: 'recipes/:id', component: RecipeDetailsComponent}
还有我的食谱细节:
export class RecipeDetailsComponent implements OnInit {
@Input() recipe! : any;
constructor(private route: ActivatedRoute,
private sharedService: SharedService) { }
ngOnInit(): void {
this.getRecipe();
}
getRecipe() : void{
const id = Number(this.route.snapshot.paramMap.get('id'));
this.sharedService.getRecipeById(id).subscribe(recipe => this.recipe == recipe);
}
}
用于测试的简单 html:
<h2>Name : {{recipe.name}}</h2>
<h2>RecipeBody: {{recipe.recipeBody}}</h2>
<h2>IntendedUse: {{recipe.IntendedUse}}</h2>
<h2>CoffeeId: {{recipe.coffeeId}}</h2>
结果: 当我点击食谱名称(recipe.component)时,它会将我重定向到: http://localhost:4200/recipes/recipes 例如 http://localhost:4200/recipes/1
在控制台中我得到:TypeError: Cannot read properties of undefined (reading 'name')
编辑: 我如何获取它:
getRecipes() : Observable<any[]> {
return this.http.get<any>(this.ApiUrl + '/Recipes')
}
getRecipeById(val:any){
return this.http.get<any>(this.ApiUrl + '/Recipes/', val);
}
【问题讨论】:
-
你看到
id被传递给this.sharedService.getRecipeById(id).subscribe了吗?请确认 -
@ShashankVivek 我已将我的方法切换为您的方法,在调试中我得到:const id = "recipes"。我猜是因为我还有localhost:4200/recipes/recipes url
标签: javascript html angular typescript rxjs