Angular2:从对象数组中通过其唯一Id获取对象的正确方法?

时间:2017-01-01 04:23:12

标签: angular mean-stack

我有两个数组:categoriesarticles

这里是数组的样子:

categories = [{id: 1, name: 'Gadgets'}, {id: 2, name: 'Artificial Intelligence'}, {id: 3, name: 'Opinions'}];   
articles = [{id: 1, categoryId: 3, title: 'Title 1', body: 'Body Text 1'}, {id: 2, categoryId: 1, title: 'Title 2', body: 'Body Text 2'}, {id: 3, categoryId: 1, title: 'Title 3', body: 'Body Text 3'}];

在以下新闻Feed中,categoryId需要由category.name替换。我如何从数组中获取所需的对象,以便我可以访问其name属性 - 而无需遍历视图中的categories数组?

我想在模板中执行类似{{category(article.categoryId).name}}的操作,但语法不正确。

enter image description here

Template:

<div class="col-md-8">
    <h4>{{article.title }}</h4> 
    <p>{{article.body }}</p> 
    <div class="tag tag-default">
        CategoryId: {{article.categoryId}} <!-- Need category.name -->
    </div>
   <div class="tag tag-success">
         Published: {{article.date_publish | date:'medium'}}
    </div>
    <div class="tag tag-info">
         Created: {{article.date_created  | date:'medium'}}
    </div>
</div>

ArticlesComponent

articles: Article[];
categories: Category[];

constructor(
  private _articleService: ArticleService,
  private _categoryService: CategoryService,
) {}

ngOnInit()
{
  this._articleService.getArticles().subscribe(articles => {this.articles = articles});
  this._categoryService.getCategories().subscribe(categories => {this.categories = categories});
}

1 个答案:

答案 0 :(得分:1)

您可以在html中调用一个函数来提取类别名称

<div class="col-md-8">
    <h4>{{article.title }}</h4> 
    <p>{{article.body }}</p> 
    <div class="tag tag-default">
        CategoryId: {{categoryname(article.categoryId)}} <!-- Need category.name -->
    </div>
   <div class="tag tag-success">
         Published: {{article.date_publish | date:'medium'}}
    </div>
    <div class="tag tag-info">
         Created: {{article.date_created  | date:'medium'}}
    </div>
</div>

并在您的组件中,您可以在this.categories

中搜索它
    articles: Article[];
    categories: Category[];

    constructor(
      private _articleService: ArticleService,
      private _categoryService: CategoryService,
    ) {}

    ngOnInit()
    {
      this._articleService.getArticles().subscribe(articles => {this.articles = articles});
      this._categoryService.getCategories().subscribe(categories => {this.categories = categories});
    }

  categoryname(id: string){
      console.log(id);
      return this.categories[id];// add your code here if your array syntax is different, you can use lodash also
   }

我认为你也可以使用{{categories[article.categoryId]}}如果你的数组很简单并将html部分放在*ngIf中以防止未定义的错误