2017-02-13 10 views
0

我在一个组件下面的代码:如何在组件中显示观察项?

ngOnInit(): void 
    { 
     const source = this.categoryService.getCategories(); 
     const sourceedit = source.subscribe(aff => console.log(aff)); 
     const example = source.map((categor) => categor.map((categories) => { 
     const links = this.categoryService.countCategoryLinks(categories.id) 
        .subscribe(valeur => console.log(valeur)); 
      return categories.id 
     })); 
     const categories = example.subscribe(val => console.log("valeur: "+val)); 
    } 

结果如下控制台: enter image description here

在我的.ts模板文件,我有以下几点:

<tr *ngFor="let category of categories | async; let id = index"> 
     <td> 
      <label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect mdl-data-table__select" for="row[3]"> 
      <input type="checkbox" id="row[3]" class="mdl-checkbox__input"/> 
      </label> 
     </td> 
     <td class="mdl-data-table__cell--non-numeric"><a [routerLink]="['/category/links']"></a>{{category.categoryName }} 
     </td> 
     <td class="mdl-data-table__cell--non-numeric">{{category.categoryName}} 
     </td> 
     <td #category.id><i (click)="deleteCategory(id)" class="material-icons">delete</i> 
     </td> 
</tr> 

并没有显示任何内容。 我想在表格中显示类别和计数结果。

在此先感谢和诚挚的问候

回答

1

从提供的代码它看起来并不像你设置this.categories等于从服务器/服务的subscribe()语句中的响应。

你需要像做以下,以确保您*ngFor="let category of categories可以显示的类别收集数据,假设getCategories()返回映射到JSON的Observable<Category[]>或类似的观察的集合的方法:

服务:

getCategories(): Observable<Category[]> { 
    return this.http.get(this.categoriesUrl) 
     .map((res: Response) => res.json() as Category[]) 
     .catch(err => console.log(err)); 
} 

组件:

this.categoryService.getCategories().subscribe(categories => this.categories = categories); 

这同样适用于计数。您需要确保您设置的类别变量或类似等于每个类别的计数。

TS:

getCount(categoryId: number): { 
    this.categoryService.countCategoryLinks(categories.id).subscribe(valeur => this.categories[categories.id].valeur = valeur); 
} 

HTML:

<td>Count: {{getCount(category.id)}}</td> 
+0

你好,对于类别书面方式 '' this.categories =此.categoryService.getCategories();''就够了。谢谢 –

0

这里是溶液的问题:

ngOnInit(): void 
{ 
    this.categories = this.categoryService.getCategories(); 
    const example = this.categories 
     .mergeMap((categor) => categor 
      .map((myCateg) => { 
     this.categoryService.countCategoryLinks(myCateg.id) 
      .map(numlinks => { 
       myCateg.numlinks = numlinks.count; 
       return myCateg; 
      }) 
       //Object.assign(myCateg,{numLinks: numlinks})) 
      .subscribe(value => console.log(value)); 
     return myCateg 
    })); 

      example.subscribe(val => console.log("value2: "+val)); 

}