2016-11-23 156 views
1

我使用異步管道將數據傳遞給子組件,但我希望通過「mimetype」的值來過濾數據。但是,當我添加我的過濾器時,我不會拾取添加到流中的任何新對象。例如;以下作品完美Angular/2 |過濾異步流

<asset-list [assets]="assets$ | async"></asset-list> 

裏面的子組件我正在循環顯示一個列表的資產。不過,如果我加入我的濾水管例如

<asset-list [assets]="assets$ | async | imageFilter"></asset-list> 

我不再拿起流中的任何改變。我的管道讀取如下:

import { Injectable, Pipe, PipeTransform } from '@angular/core'; 

@Pipe({ 
    name: 'imageFilter' 
}) 
@Injectable() 
export class AssetImagesPipe implements PipeTransform { 

    transform(assets: any[]) { 

     var images = []; 

     for(let i in assets) { 

      if(assets[i].mimetype.substring(0,5) == 'image') 
      { 
       images.push(assets[i]); 
      } 
     } 

     return images; 
    } 
} 

任何意見是非常感謝。

回答

5

有兩種可能的方式:

設置你管到pure: falsehttps://angular.io/guide/pipes#pure-and-impure-pipes

或異步管道之前使用它..

不純管:

@Pipe({ 
    name: 'imageFilter', 
    pure: false 
}) 
export class AssetImagesPipe implements PipeTransform { 

    transform(assets: any[]) { 
     if (!assets || !assets.length) return []; 
     return assets.filter(...); 
    } 
} 

async-pipe之前:

@Pipe({ 
    name: 'imageFilter$' 
}) 
export class AssetImagesAsyncPipe implements PipeTransform { 

    transform(assets$: Observable<any[]>) { 
     if (!assets$) return undefined; 
     return assets$.map(assets => assets.filter(...)); 
    } 
} 

查看我的郵件:https://plnkr.co/edit/Q2Yw2TjdpGqA4dWBxfZ0?p=preview

+0

謝謝,高超的回答。我選擇了兩項,因爲不純的管道似乎有很大的開銷。 – prime

+0

對於一些重複值的任何其他方式最多5次然後創建新的數組,並從數組中刪除該值?我有這種陣列:[「info.specificAllergy」,「info.specificAllergy」,「info.specificAllergy」,「info.specificAllergy」,「info.specificAllergy」,「info.existingMedicalCondition」,「info.existingMedicalCondition」, 「info.existingMedicalCondition」,「info.existingMedicalCondition」,「info.existingMedicalCondition」] –