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

Reuse pipe filter result for other element

official angular2 pipes documentation的一个例子,我想知道是否有可能实现以下目标:

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

其中 "hasFlyingHeroes" 使用 ngFor 的过滤值,以免将 flyingHeroes 过滤掉两次。

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

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

@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两次是正常的,因为它有几种修改方式,所以缓存过滤集不会有任何好处。

对于通过特定public方法(例如add)严格修改的模型,可以使那里的缓存无效并缓存过滤后的集合,将调用getFlying只有一次。