【问题标题】:angular 2 sequential pipes有角度的2个顺序管道
【发布时间】:2016-07-26 12:19:36
【问题描述】:

如何顺序使用两个管道?

<div class="thread" *ngFor="thread of threadlist | bookmarkPipe | threadPipe"></div>

具体来说,我的线程有一个书签:布尔属性以及标签属性(单元、任务、子任务)。 所以我想要实现的是第一个管道过滤所有标记的线程,然后应用第二个管道(下)

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

【问题讨论】:

    标签: filter angular pipe forum


    【解决方案1】:

    其实也没什么特别的。第二个管道将接收前一个管道的值:

    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
    

    如果我们将pipe2 应用于先前的结果,data | pipe1 将返回[ 'val2', 'val3' ] 并返回[ 'val3' ]

    查看对应的plunkr:https://plnkr.co/edit/EpKMitR3w89fRiyGYQz7?p=preview

    【讨论】:

    • 您好,感谢您的快速回复,所以基本上是#elt of data |管道1 |管道2 | pipe3 会是这样的意思吗? ((#elt 数据 | pipe1) | pipe2) |管道 3
    • 另外,我刚刚在 angular.io 上读到,鼓励使用管道进行列表过滤,并且应该在组件内部完成。但是我认为在这种情况下,用户只单击一次过滤器并且只调用一次管道,应该可以吗?
    • 我认为这是正确的方法。当您拥有“非纯”(有状态)管道时,情况会有所不同,因为每次更新绑定时都会调用管道。有关更多详细信息,请参阅此 Mark Rajcok 的精彩答案:stackoverflow.com/questions/34456430/…。我会对 angular.io 网站上的链接感兴趣 ;-)
    • 它就在“无 FilterPipe 或 OrderByPipe”下方的底部 angular.io/docs/ts/latest/guide/pipes.html 干杯!当然,我的意思是上面“不鼓励”:)
    • 感谢您的链接!是的,它适用于不纯的管道;-)
    猜你喜欢
    • 2017-12-15
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    • 2017-07-03
    • 2017-05-31
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    相关资源
    最近更新 更多