如何在Plunker中从关联对象获取数据,实现点击按钮展示沙拉配料名称
解决沙拉配料名称展示问题
看来你已经搭好基础框架啦,只是几个小细节需要调整,咱们一步步把它搞定:
第一步:修正食谱对象的获取逻辑
你现在用filter查找目标食谱,但filter会返回匹配项组成的数组,而你需要的是单个食谱对象。换成find方法更合适——毕竟每个食谱的id是唯一的:
getSalad(param: number) { // 注意:你的recipe.id是字符串类型,param是数字,要做类型转换 const targetRecipe = this.recipes.find(rec => rec.id === param.toString()); if (targetRecipe) { this.getNameOfIngredients(targetRecipe); } else { console.log("未找到对应的食谱"); } }
第二步:实现配料名称的匹配与收集
接下来,getNameOfIngredients需要根据食谱里的recipein数组(存储配料id),去ingredients数组里匹配对应的配料名称并收集起来:
// 定义一个属性存储最终的配料名称列表 ingredientNames: string[] = []; getNameOfIngredients(recipe: any) { // 清空之前的结果,避免重复累积 this.ingredientNames = []; recipe.recipein.forEach((ingId: number) => { // 查找对应id的配料 const matchedIngredient = this.ingredients.find(ing => ing.id === ingId.toString()); if (matchedIngredient) { this.ingredientNames.push(matchedIngredient.name); } }); }
第三步:模板中的按钮与展示逻辑
在模板里给按钮绑定点击事件,传入对应食谱的id,再把收集到的配料名称展示出来:
<!-- 遍历食谱生成对应按钮 --> <div *ngFor="let recipe of recipes"> <button (click)="getSalad(+recipe.id)">查看{{ recipe.name }}的配料</button> </div> <!-- 展示配料列表 --> <div *ngIf="ingredientNames.length > 0"> <h3>配料清单:</h3> <ul> <li *ngFor="let name of ingredientNames">{{ name }}</li> </ul> </div>
关键注意事项
- 你的
id字段是字符串类型,但recipein里存的是数字类型,匹配时一定要做好类型转换,避免匹配失败。 - 加入存在性检查(比如
if (targetRecipe)),防止找不到对象时出现报错。
调整完这些,点击按钮就能正确展示对应沙拉的配料名称啦!
内容的提问来源于stack exchange,提问作者Slip
相关产品推荐
相关产品推荐

