gpt4 book ai didi

angular - 如何使用 ngrx 和 effects 订阅 Action 成功回调

转载 作者:太空狗 更新时间:2023-10-29 16:54:03 24 4
gpt4 key购买 nike

我正在尝试做一些简单的事情 - 在一些实体保存之后(使用 http 请求)我想导航回列表路线。问题是:如何订阅成功的 Action (或者可能是 reducer 或 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));

reducer :

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

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

关于angular - 如何使用 ngrx 和 effects 订阅 Action 成功回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43226681/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com