Executing code after dispatch is completed while using ngrx
Quick answer : You can't.
As you said, dispatch
is asynchronous.
What you should do is use @ngrx/effects. It's nearly the same as using addAuthorAction
except that instead of calling a function, you "catch" the dispatched actions and do something just after they've been applied by the reducers.
So what I do in general, is that I divide my actions in 3, for example :
FETCH_USER
FETCH_USER_SUCCESS
FETCH_USER_ERROR
FETCH_USER
is just used to toggle a boolean so I can display a spinner while fetching the userI catch this action from an effect and make an http request to fetch the user
If the http response is OK and I have the info I'm looking for, I dispatch from the effect
FETCH_USER_SUCCESS
with the response as payload, otherwise I dispatchFETCH_USER_ERROR
and I toggle the boolean to false (so we can try to fetch him again for example).
So in your example, if you want to console.log
something AFTER the FETCH_USER_SUCCESS, just use another effect to catch the FETCH_USER_SUCCESS and do what you want to here.
Tested with
"@ngrx/core": "^1.2.0",
"@ngrx/effects": "^7.4.0",
"@ngrx/router-store": "^7.4.0",
"@ngrx/store": "^7.4.0",
"@ngrx/store-devtools": "^7.4.0",
This will also work:
import { ofType, Actions } from '@ngrx/effects';
// Constructor
constructor(
private _actions$: Actions,
private _store: Store<any>,
) { }
// YOUR METHOD
this._store.dispatch(<ACTION>);
this._actions$.pipe(ofType(<ACTION_NAME>)).subscribe((data: any) => {
console.log(data); // returned state data
})
With ngrx you can listen to actions like this:
constructor(private actionsSubject$: ActionsSubject, private store: Store<AppState>) {}
ngOnInit() {
this.actionsSubject$.pipe(
takeUntil(this.unsubscribe$), // optional
filter((action) => action.type === SimsActionTypes.SimEditedSuccess)
).subscribe(({payload}) => {
console.log(payload)
)
}
When you dispatch FIRST_ACTION use an effect to make the HTTP request. In the effect, when you have the response back, fire off a SECOND_ACTION with the response as the payload. Then just listen for SECOND_ACTION in your controller .ts file