【问题标题】:Is it recommended to subscribe to the store (ngRx) inside a pipe?是否建议订阅管道内的商店(ngRx)?
【发布时间】:2020-03-26 14:14:14
【问题描述】:

在某些情况下,我们需要从 store 中获取数据来做一些工作,是否可以在管道中调用 store ?

我想知道这是否会损害我的 Angular 应用并导致一些性能问题

基本示例:

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

【问题讨论】:

  • 我不知道你为什么需要它,请发布你的代码
  • 没有代码,但我只想知道订阅和管道内数据的特征是否是一个好主意,因为我害怕这样做会导致一些性能问题。希望你能明白。

标签: angular performance ngrx rxjs6


【解决方案1】:

您最终会得到一个与async 管道基本相同的管道函数,因为您必须管理订阅并将视图标记为在存储更改时为脏视图。工作量很大,看看异步源代码就知道它有多复杂。

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

另一种方法是在模板中使用带有异步的选择器,然后将额外的参数传递给您的管道。

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

【讨论】:

  • 这个想法看起来很不错,但众所周知,一个有角的管道会在几毫秒内触发很多次。在管道上做这样的工作是个好主意吗?
猜你喜欢
  • 1970-01-01
  • 2019-03-06
  • 1970-01-01
  • 2019-08-18
  • 1970-01-01
  • 2022-10-21
  • 2018-02-16
  • 1970-01-01
  • 2020-06-25
相关资源
最近更新 更多