简体   繁体   English

angular2管道用于多个参数

[英]angular2 pipe for multiple arguments

I have a array of thread objects, each thread object with the properties 我有一个线程对象数组,每个线程对象都有属性

unit:number
task:number
subtask:number

I want to create a pipe to filter after these threads, so far I have a working pipe like below. 我想创建一个管道来过滤这些线程,到目前为止我有一个像下面这样的工作管道。 I'm not really satisfied with it yet and wanted to ask you guys if there is a more elegant solution? 我对它还不是很满意,想问你们是否有更优雅的解决方案?

HTML: HTML:

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

Pipe.ts 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
    }
  }
}

You are implementing your pipe the right way, but you are basically re-inventing the Array.prototype.filter mechanism in your code. 您正在以正确的方式实现管道,但您基本上是在代码中重新发明Array.prototype.filter机制。 A simpler way will be: 一种更简单的方法是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM