在某些情况下,我们需要从 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;
}
}
最佳答案
您最终会得到一个与 async
基本相同的管道函数。管道,因为您必须管理订阅并在存储更改时将 View 标记为脏。工作量很大,请查看异步源代码以了解它的复杂程度。
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;
}
}
关于angular - 是否建议订阅管道内的商店(ngRx)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59130911/