我正在尝试根据categoryId
检索多个值这是我的代码
// mock-data而不是json
private recipes: Recipe[] = [
new Recipe('recipe-a1', 'breakfast'),
new Recipe('recipe-a2', 'breakfast'),
new Recipe('recipe-a3', 'breakfast'),
new Recipe('recipe-a4', 'lunch')
];
// recipe.service.ts
//这是对的吗?如何使用categoryId检索多条记录?
getRecipesByCategoryId(categoryId: string) {
return this.recipes[categoryId];
}
//这是我的组件recipe.component.ts //错误:this.recipes未定义
constructor(private recipeService: RecipeService) {}
ngOnInit() {
this.recipes = this.recipeService.getRecipesByCategoryId('breakfast');
} // is this correct?
//食谱对象
export class Recipe {
constructor(public name: string,
public categoryId: string){}
}
答案 0 :(得分:3)
您可以根据recipes
param
categoryId
上应用过滤器
getRecipesByCategoryId(categoryId: string) {
return this.recipes.filter(recipe => recipe.categoryId === categoryId);
}