Reputation: 51
In some cases we need to fetch data from the store to do some work, is it ok to call the store inside a pipe ?
I want to know if this will harm my angular app and cause some performance issues.
Basic example:
@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;
}
}
Upvotes: 4
Views: 1711
Reputation: 54791
You will end up with a pipe function that is basically identical to the async
pipe, because you have to manage a subscription and mark the view as dirty when the store changes. It's a lot of work, and take a look at the async source code to get an idea of how complex it is.
https://github.com/angular/angular/blob/master/packages/common/src/pipes/async_pipe.ts
The alternative is to use the selector with async in the template, and then pass extra parameters to your pipe.
<app-component [value]="selector$ | async | myPipe:value"></app-component>
If you really must do it as your own pipe, then try extending the async pipe.
@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;
}
}
Upvotes: 6