2017-01-01 3 views
2

私は2つの配列:categoriesarticlesを持っています。 category.nameによって置き換えられるするには、次のニュースフィード、categoryIdニーズにAngular2:オブジェクトの配列から一意のIDでオブジェクトを取得する適切な方法ですか?

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'}]; 

:ここ

は、配列がどのように見えるかです。ビューから配列categoriesをループすることなく、名前プロパティにアクセスできるように、配列から必要なオブジェクトを取得するにはどうすればよいですか?

テンプレートに{{category(article.categoryId).name}}のようなことをしたいのですが、正しい構文ではありません。あなたは、カテゴリ名

を抽出するために、あなたのhtml内の関数を呼び出すことができます

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}); 
} 
+0

私の解決策はあなたの場合に働いていますか?ヴィーブク –

答えて

1

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> 
<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]}}を使用すると、未定義のerrosから防ぐために*ngIfでHTML部分を置くことができると思います

関連する問題