how to subscribe to action success callback using ngrx and effects

You can subscribe to actions in components as well:

[...]
import { Actions } from '@ngrx/effects';
[...]

@Component(...)
class SomeComponent implements OnDestroy {
    destroyed$ = new Subject<boolean>();

    constructor(updates$: Actions) {
        updates$.pipe(
           ofType(PostActions.SAVE_POST_SUCCESS),
           takeUntil(this.destroyed$)
        )
        .subscribe(() => {
           /* hooray, success, show notification alert etc.. */
        });
    }

    ngOnDestroy() {
        this.destroyed$.next(true);
        this.destroyed$.complete();
    }
}

you need to have a selector that give you the latest post

this.latestPost$ = this.store.select(fromRoot.getPost);

then you can subscribe to this.latestPost$ observable and redirect to your new route assuming you have declared latestPost$: Observable<Post>; in your component.

for more details see this example app https://github.com/ngrx/example-app


Based on this:https://netbasal.com/listening-for-actions-in-ngrx-store-a699206d2210 with some small modifications, as since ngrx 4 there is no Dispatcher anymore, but instead ActionsSubject:

import { ActionsSubject } from '@ngrx/store';
import { ofType } from "@ngrx/effects";

subsc = new Subscription();

constructor(private actionsSubj: ActionsSubject, ....) { 
  this.subsc = this.actionsSubj.pipe(
     ofType('SAVE_POST_SUCCESS')
  ).subscribe(data => {
     // do something...
  });
}

ngOnDestroy() {
  this.subsc.unsubscribe();
}

Tags:

Angular

Ngrx