0

如果用户想按一些不同的标准过滤他们的数据,我有多个不同的管道,我想打开和关闭它们。我将如何激活/停用当前在搜索中使用的管道或构建一个行为不同的管道,具体取决于用户单击的按钮?

例如,两个管道/过滤器看起来像这样......

//cloud.pipe.ts
import {Pipe} from '@angular/core';
import {Hero} from './hero';

@Pipe({
  name: 'Cloud'
})
export class CloudPipe{
  transform(value) {
    if (value == null) {
      return null;
    }
    return value.filter(hero => {
      return hero.cloud === true;
    });
  }
}
//location.pipe.ts
import {Pipe} from '@angular/core';
import {Hero} from './hero';
import { HeroService } from './hero.service';
import { HeroesComponent } from './heroes.component';

@Pipe({
  name: 'Location'
})

export class LocationPipe{
  transform(value) {
    if (value == null) {
      return null;
    }
    return value.filter(hero => {
      return hero.location < 500;
    });
  }
}

然后我想让用户切换不同的过滤器按钮并将管道添加/删除到列表中。像这样的事情最好的方法是什么?

<!--Toggle what pipes should be used in search-->
<!--For example how can I construct the "updatePipe" function for doing this?-->
<button id="activateCloud" (click)="updatePipe()"></button>
<button id="activateLocation" (click)="updatePipe()"></button>
<!--Is it possible to have: neither of the pipes active, both at the same time or just one at the time? How can I do this?-->
<div *ngFor="let hero of heroes | Cloud | Location ></div> 

我宁愿不要将所有东西都放在同一个管道中,因为我想扩展每个管道以在将来做更多事情。因此,每个管道都应该“是它自己的”,并且彼此独立工作,但同时在必要时与其他管道一起工作。

4

1 回答 1

0

您可以创建一个包装管道,根据要使用的参数转发到其他管道,例如

<div *ngFor="let hero of heroes | myPipe:'Cloud':'Location'" ></div> 
@Pipe({
  name: 'myPipe'
})
export class MyPipe{
  locationPipe = new LocationPipe();
  cloudPipe = new CloudPipe();
  constructor() {
    pipes = {
      locationPipe: this.locationPipe,
      cloudPipe: this.clouldPipe
    };
  }

  transform(value, param1, param2) {
    var result = value;
    if(pram1) {
      result = this.pipes[param1].transform(result);
    }
    if(pram2) {
      result = this.pipes[param1].transform(result);
    }
  }
}

或者如果管道列表用作数组

<div *ngFor="let hero of heroes | myPipe:['Cloud':'Location']" ></div> 
@Pipe({
  name: 'myPipe'
})
export class MyPipe{
  locationPipe = new LocationPipe();
  cloudPipe = new CloudPipe();
  constructor() {
    pipes = {
      locationPipe: this.locationPipe,
      cloudPipe: this.clouldPipe
    };
  }

  transform(value, params) {
    var result = value;
    for(var p in params) {
      result = this.pipes[p].transform(result);
    }
  }
}
于 2016-07-31T14:56:17.127 回答