如何使用ngrx和effects订阅动作成功回调 [英] how to subscribe to action success callback using ngrx and effects
本文介绍了如何使用ngrx和effects订阅动作成功回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试做简单的事情-保存某些实体后(使用http请求) 我想导航回列表路线.问题是:如何订阅成功动作(或者可能是成功者或效果者?)
I'm trying to do simple thing - after some entity saved (using http request) I want to navigate back to list route. The problem is : how to subscribe to success action (or may be reducer or effect?)
这是我的操作代码:
static SAVE_POST = '[POST] Save POST';
savePOST(Post): Action {
return {
type: PostActions.SAVE_POST,
payload: Post
};
}
static SAVE_POST_SUCCESS = '[POST] Save POST Success';
savePOSTSuccess(Post): Action {
console.log('action: savePostSuccess')
return {
type: PostActions.SAVE_POST_SUCCESS,
payload:Post
};
}
我正在使用效果:
@Effect() savePost$ = this.update$
.ofType(PostActions.SAVE_POST)
.map(action => action.payload)
.switchMap(post => this.svc.savePost(post))
.map(post => this.postActions.savePOSTSuccess(post));
减速器:
const initialState: PostListState = [];
export default function (state = initialState, action: Action): PostListState {
switch (action.type) {
case PostActions.LOAD_POST_SUCCESS: {
return action.payload;
}
case PostActions.SAVE_POST_SUCCESS: {
console.log('SavePOST SUCCESS',action.payload)
let index = _.findIndex(state, {_id: action.payload._id});
if (index >= 0) {
return [
...state.slice(0, index),
action.payload,
...state.slice(index + 1)
];
}
return state;
}
default: {
return state;
}
}
}
在我的组件中,我想订阅成功回调:
in my component i want to subscribe to success callback:
handlePostUpdated($event) {
this.post = this.code;
let _post: Post = Object.assign({}, { _id: this.id, name: this.name, text: this.post });
this.store.dispatch(this.postActions.savePOST(_post)); //not have "subscribe" method
}
感谢帮助
推荐答案
您还可以订阅组件中的操作:
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();
}
}
这篇关于如何使用ngrx和effects订阅动作成功回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文