how to subscribe to action success callback using ngrx and effects

笑着哭i 提交于 2019-11-28 04:45:27

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$
            .ofType(PostActions.SAVE_POST_SUCCESS)
            .takeUntil(this.destroyed$)
            .do(() => /* hooray, success, show notification alert ect.. */)
            .subscribe();
    }

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

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';

subsc = new Subcription();

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

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

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

It will be better if you also add your reducer function code and show how the saved post affects your state, on savePOSTSuccess action.

In general, you may put an "editing" boolean property in your post state.

On the reducer, you can set a flag value to !editing state by setting the property to false.

Then, you may add a selector on that property and show or hide the form according to this property.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!