angular2管道用于多个参数

时间:2016-04-05 10:33:43

标签: filter angular forum angular2-pipe

我有一个线程对象数组,每个线程对象都有属性

unit:number
task:number
subtask:number

我想在这些线程之后创建一个过滤管道,到目前为止我有一个像下面这样的工作管道。我对此并不满意,想问你们是否有更优雅的解决方案?

HTML:

<div class="thread-item" *ngFor="#thread of threadlist | threadPipe:unitPipe:taskPipe:subtaskPipe"></div>

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
    }
  }
}

1 个答案:

答案 0 :(得分:6)

您正在以正确的方式实现管道,但您基本上是在代码中重新发明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;
      });
    }
  }
}