我正在尝试做一些简单的事情 - 在一些实体保存后(使用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
};
}
Run Code Online (Sandbox Code Playgroud)
我正在使用效果:
@Effect() savePost$ = this.update$
.ofType(PostActions.SAVE_POST)
.map(action => action.payload)
.switchMap(post => this.svc.savePost(post))
.map(post => this.postActions.savePOSTSuccess(post));
Run Code Online (Sandbox Code Playgroud)
减速器:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
在我的组件中,我想订阅成功回调:
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
}
Run Code Online (Sandbox Code Playgroud)
感谢帮助
ols*_*lsn 46
您也可以订阅组件中的操作:
[...]
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();
}
}
Run Code Online (Sandbox Code Playgroud)
AJT*_*T82 28
基于此:https://netbasal.com/listening-for-actions-in-ngrx-store-a699206d2210进行了一些小修改,因为ngrx 4已经没有Dispatcher了,但是ActionsSubject:
import { ActionsSubject } from '@ngrx/store';
import { ofType } from "@ngrx/effects";
subsc = new Subcription();
constructor(private actionsSubj: ActionsSubject, ....) {
this.subsc = actionsSubject.pipe(
ofType('SAVE_POST_SUCCESS')
).subscribe(data => {
// do something...
});
}
ngOnDestroy() {
this.subsc.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18109 次 |
| 最近记录: |