2017-01-01 3 views
2

У меня есть два массива: categories и articles.Angular2: Правильный метод получения объекта по его уникальному идентификатору из массива объектов?

Вот что массивы выглядеть следующим образом:

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

В следующей ленте новостей, то categoryId надо заменить на category.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}); 
} 
+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 для предотвращения неопределенной erros