如何使用Angular 2(打字稿)按类别检索多个记录?

时间:2017-02-04 16:09:53

标签: angular typescript

我正在尝试根据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){}
}

1 个答案:

答案 0 :(得分:3)

您可以根据recipes param

categoryId上应用过滤器
getRecipesByCategoryId(categoryId: string) {
    return this.recipes.filter(recipe => recipe.categoryId === categoryId); 
}