Is it possible to have some sort of 'callback function' or watcher to an NGRX Effect? The use case is, I'm trying to persist state across browser refresh. I'd like to call my cache service to save the app state after each effect has run. Currently, I'm doing this by adding this to every effect:
tap(() => setTimeout(() => this.cacheService.saveAppState()))
It feels like there should be a better way to accomplish this?
Yes, there is a better way. You can implement OnRunEffects
on the effects classes. For example:
@Injectable()
export class OrderStoreEffects implements OnRunEffects {
// Resolves to either QueryCompleted or QueryFailed
@Effect()
queryOrdersFromProduct$: Observable<Action> = this.actions$.pipe(...);
// Resolves to either QueryCompleted or QueryFailed
@Effect()
queryOrdersFromWorkCenter$: Observable<Action> = this.actions$.pipe(...);
constructor(...) {}
ngrxOnRunEffects(resolvedEffects$: Observable<EffectNotification>) {
return resolvedEffects$.pipe(tap(effect => console.log({ effect })));
}
}
The resolvedEffects$
observable emits every time that an effect in the OrderStoreEffects
class is executed and resolved.
The emitted values look like this:
Which gives you some further possibilities to apply filters or other logic.
For more information about the OnRunEffects
interface, check the docs
you don't need anything special. Write separate effect with function you've shown and just don't filter action type in it but go directly:
this.$actions.pipe(/* your logic here */)
so that will run for all actions.
now you can have withLatestFrom
to get current state and do whatever you need with it.
[UPDATE]
This is something i'd not implement in effects but in canDeactivate
router guards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With