angular2 pipe for multiple arguments

[亡魂溺海] 提交于 2020-01-04 01:51:27

问题


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:

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


You are implementing your pipe the right way, but you are basically re-inventing the Array.prototype.filter mechanism in your code. 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;
      });
    }
  }
}


来源:https://stackoverflow.com/questions/36423903/angular2-pipe-for-multiple-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!