angularreduxngrxngrx-effects

Executing code after dispatch is completed while using ngrx


In my sample Angular 2 application , I am using ngrx/store and ngrx/effects for state management.

Below is one of the function in a component to add a new item.

addAuthor() {
    
    this.store.dispatch(addAuthorAction(this.fg.value));
    console.log('2')        
} 

In the above code this.store.dispatch(addAuthorAction(this.fg.value)); takes care of making an AJAX call to server and adding a new author to database, which is working fine.

And because this.store.dispatch(addAuthorAction(this.fg.value)); is an async action , console.log("2") statement gets executed even before the AJAX call is completed.

My question is , what needs to be modified so that console.log gets executed after store.dispatch is done.


Solution

  • 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 :

    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.