如何依次使用两个管道?
<div class="thread" *ngFor="thread of threadlist | bookmarkPipe | threadPipe"></div>
具体来说,我的线程有一个书签: bool 属性以及标签属性(单元、任务、子任务)。 所以我想要实现的是,第一个管道过滤所有已添加书签的线程,然后应用第二个管道(如下)
export class ThreadPipe implements PipeTransform{
transform(array:Thread[], [unit,task,subtask]):any{
//See all Threads
if(unit == 0 && task == 0 && subtask == 0){
return array
}
//See selected Units only
if(unit != 0 && task == 0 && subtask == 0){
return array.filter(thread => {
return thread.unit === unit;
});
}
//See selected Units and Tasks
if (unit != 0 && task != 0 && subtask == 0){
return array.filter(thread => {
return thread.unit === unit && thread.task === task;
});
}
// See selected units, tasks, subtask
if (unit != 0 && task != 0 && subtask != 0){
return array.filter(thread => {
return thread.unit === unit && thread.task === task && thread.subtask === subtask;
});
}
}
}
最佳答案
其实也没有什么特别要做的。第二个管道将接收前一个管道的值:
data -> Pipe1 -> filtered data (#1) -> Pipe2 -> filtered data (#2)
例如,如果我有一个数组 [ 'val1', 'val2', 'val3' ]
并使用以下管道:
@Pipe({
name:'pipe1'
})
export class Pipe1 {
transform(data) {
return data.filter((d) => {
return d!= 'val1';
});
}
}
@Pipe({
name:'pipe2'
})
export class Pipe2 {
transform(data) {
return data.filter((d) => {
return d!= 'val2';
});
}
}
通过在 ngFor
中使用以下表达式:
#elt of data | pipe1 | pipe2
data | pipe1
将返回[ 'val2', 'val3' ]
并返回[ 'val3' ]
如果我们应用pipe2
根据之前的结果。
查看相应的plunkr:https://plnkr.co/edit/EpKMitR3w89fRiyGYQz7?p=preview .
关于filter - Angular 2 个连续管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36445327/