重复使用管道过滤器结果为其他元素

时间:2016-08-28 20:32:03

标签: angular angular2-pipe

查看official angular2 pipes documentation的示例,我想知道是否有可能实现以下目标:

    <div [hidden]="hasFlyingHeroes">
      <span>Heroes fly!</span>
    </div>
    <div *ngFor="let hero of (heroes | flyingHeroes)">
      {{hero.name}}
    </div>

其中&#34; hasFlyingHeroes&#34;使用ngFor的过滤值,以便不过滤掉flyingHeroes两次。

1 个答案:

答案 0 :(得分:0)

管道用于分享不相关的数据之间的共同行为。

具有特定行为的数据片段可以表示为模型,

@Injectable()
class Heroes extends Array {
  getFlying() {
    return this.filter(hero => hero.canFly);
  }

  hasFlying() {
    return !!this.getFlying().length;
  }  
}

<div [hidden]="heroes.hasFlying()">
  <span>Heroes fly!</span>
</div>
<div *ngFor="let hero of heroes.getFlying()">
  {{hero.name}}
</div>

对于用扩展数组表示的模型,调用getFlying两次是正常的,因为它有几种方法可以修改,因此缓存过滤后的集合将不会有任何好处。

对于严格通过特定公共方法(例如add)进行修改的模型,可以使缓存无效并缓存已过滤的集合,getFlying将仅被调用一次。