【问题标题】:Angular - Impure pipe vs functionAngular - 不纯管道与函数
【发布时间】:2018-11-27 01:53:05
【问题描述】:

我正在 Angular2 中对数组执行过滤操作。当数组中的元素更改时,不会触发纯管道。因此,我必须使用不纯的管道或使用组件内部的函数进行过滤,如下所示。

*ngFor="let item of items | impureFilterPipe"

或者,

<!-- component.html -->
*ngFor="let item of filterFunction(items)"

// component.ts
sortFunction(items) { return items.sort(); }

据我所知,在模板中绑定函数在性能方面很糟糕。但是,我看不出使用不纯管道而不是函数有什么区别。我想知道的是上面这两种方法的性能有什么区别吗?

【问题讨论】:

标签: angular data-binding angular-pipe angular-changedetection


【解决方案1】:

正如 cmets 中所指出的,Angular 团队自己建议不要使用管道来过滤或排序集合。解释是这些管道基本上会在每个变更检测周期运行,即使是小的集合也使得它们非常昂贵。

标准解决方案是控制何时进行排序操作,例如:

*ngFor="let item of filteredItems"

ngOnInit() {
  this.filteredItems = this.items.filter(/***/);
  ...
}

如果您想按需运行,也可以将该逻辑包装在自己的函数中。

【讨论】:

    【解决方案2】:

    不建议使用不纯的管道。它会影响你的表现。 即使源没有更改,它也会被调用,因此正确的替代方法是更改​​返回对象的引用。或者更好的是,将过滤逻辑移动到组件级别。

    // inside component
    someMethod():void{
      this.items.push(newItem);
    this.items = Object.clone(this.items);
    }
    
    
    
    @Pipe({
        name: 'showfilter'
    })
    
    export class ShowPipe {
        transform(value) {
            return value.filter(item => {
                return item.visible == true;
            });
        }
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-10
      • 1970-01-01
      • 1970-01-01
      • 2016-07-20
      • 2017-06-17
      • 2017-12-11
      • 2018-08-22
      相关资源
      最近更新 更多