建议在管道内订阅商店(ngRx)吗?

时间:2019-12-01 23:19:43

标签: angular performance ngrx rxjs6

在某些情况下,我们需要从存储中获取数据以执行某些工作,可以在管道内调用存储吗?

我想知道这是否会损害我的角度应用程序并引起一些性能问题

基本示例:

@Pipe({name: 'myPipe'})
export class MyPipe implements PipeTransform {

    _result = null;

    constructor(private _store: Store<AppState>) {}

      transform(value: any, params?: any): any {
        this._store.select(selector).subscribe(data => {
          // traitement
        });

        return _result;
      }
    }

1 个答案:

答案 0 :(得分:3)

您最终将获得与async管道基本相同的管道功能,因为您必须管理预订并在商店更改时将视图标记为脏。这是很多工作,请看一下异步源代码以了解它的复杂程度。

https://github.com/angular/angular/blob/master/packages/common/src/pipes/async_pipe.ts

另一种方法是将选择器与模板中的async一起使用,然后将其他参数传递给管道。

<app-component [value]="selector$ | async | myPipe:value"></app-component>

如果您确实必须将其作为自己的管道来执行,请尝试扩展异步管道。

@Pipe({name: 'myPipe', pure: false})
export class MyPipe extends AsyncPipe {

    _result = null;

    constructor(private _store: Store<AppState>, _ref: ChangeDetectorRef) {
       super(_ref);
    }

    transform(value: any, params?: any): any {
      const data = super.transform(this._store.select(selector));
      if(data) {
         // do work here
      }
      return _result;
    }
}
相关问题