Han*_*Che 3 forum filter angular2-pipe angular
我有一个线程对象数组,每个线程对象都有属性
unit:number
task:number
subtask:number
Run Code Online (Sandbox Code Playgroud)
我想创建一个管道来过滤这些线程,到目前为止我有一个像下面这样的工作管道.我对它还不是很满意,想问你们是否有更优雅的解决方案?
HTML:
<div class="thread-item" *ngFor="#thread of threadlist | threadPipe:unitPipe:taskPipe:subtaskPipe"></div>
Run Code Online (Sandbox Code Playgroud)
Pipe.ts
export class ThreadPipe implements PipeTransform{
threadlistCopy:Thread[]=[];
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){
this.threadlistCopy=[];
for (var i = 0; i<array.length;i++){
if(array[i].unit == unit){
this.threadlistCopy.push(array[i])
}
}
return this.threadlistCopy
}
//See selected Units and Tasks
if (unit != 0 && task != 0 && subtask == 0){
this.threadlistCopy=[];
for (var i = 0; i<array.length;i++){
if(array[i].unit == unit && array[i].task == task){
this.threadlistCopy.push(array[i])
}
}
return this.threadlistCopy
}
// See selected units, tasks, subtask
if (unit != 0 && task != 0 && subtask != 0){
this.threadlistCopy=[];
for (var i = 0; i<array.length;i++){
if(array[i].unit == unit && array[i].task == task && array[i].subtask == subtask){
this.threadlistCopy.push(array[i])
}
}
return this.threadlistCopy
}
}
}
Run Code Online (Sandbox Code Playgroud)
您正在以正确的方式实现管道,但您基本上是Array.prototype.filter在代码中重新创建机制.一种更简单的方法是:
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;
});
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5941 次 |
| 最近记录: |