angular – 如何使用ngrx和effects订阅动作成功回调
发布时间:2020-12-17 07:55:34 所属栏目:安全 来源:网络整理
导读:我正在尝试做一些简单的事情 – 在保存一些实体后(使用http请求) 我想导航回列表路线.问题是:如何订阅成功动作(或者可能是减速器或效果?) 这是我的行为代码: static SAVE_POST = '[POST] Save POST';savePOST(Post): Action { return { type: PostActions
我正在尝试做一些简单的事情 – 在保存一些实体后(使用http请求)
我想导航回列表路线.问题是:如何订阅成功动作(或者可能是减速器或效果?) 这是我的行为代码: 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; } } } 在我的组件中,我想订阅成功回调: 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 } 感谢帮助
您也可以订阅组件中的操作:
[...] 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(); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |