Angular - 在服务和组件中使用多个管道

时间:2018-03-27 05:01:29

标签: angularjs typescript pipe

我有类似的东西

<ul>
    <li *ngFor="let object of objects | pipeOne : filterVarOne | pipeTwo : 
         filterVarTwo">
        {{object}}
    </li>
</ul>

并将该管道传递给我的组件。我做了类似的事情

import { PipeOne } from '../pipes/one.pipe';
import { PipeTwo } from '../pipes/two.pipe';
import { ListService } from '../services/list.service';

report: any;

list: any;

filterVarOne;
filterVarTwo;

constructor(
    private _pipeOne: PipeOne,
    provate _pipeTwo: PipeTwo,
    private _listService: ListService
){
    this._listService.getList().subcribe(res => {
        this.list = res;
    })
}

applyFilter(){
    this.report = this._pipeOne.transform(this.list, this.filterVarOne);
}

有了这个我能够应用PipeOne,但如果我尝试这样的东西

applyFilter(){
    this.report = this._pipeOne.transform(this.list, this.filterVarOne);
    this.report = this._pipeTwo.transform(this.list, this.filterVarTwo);
}

显然我没有得到我期望的结果。

我的问题是:我可以在component.html的代码中合并两个Pipes ......

let object of objects | pipeOne : filterVarOne | pipeTwo : filterVarTwo

...这样的事情? (当然不是那么荒谬)

this.report = this._pipeOne.transform(this.list, this.filterVarOne) | 
this._pipeTwo.transform(this.list, this.filterVarTwo);

1 个答案:

答案 0 :(得分:0)

要使其正常工作,您需要将第一个管道的输出作为第二个管道的输入传递:

applyFilter(){
    this.report = this._pipeOne.transform(this.list, this.filterVarOne);
    this.report = this._pipeTwo.transform(this.report, this.filterVarTwo);
}

在原始代码中,pipeTwo已应用于未过滤的数据,会覆盖pipeOne变量中report的结果。