[英]How can I return from an effect with ngrx / angular5 from a callback function?
我的效果是:
@Effect() /* sends request to httpService with params as login credentials on instance of loginAction. */
login$: Observable<Action> = this.actions$
.instanceOf(LoginActions.LoginAction)
.switchMap(
action => {
return this.loginHttpService.login(action.payload)
.map( (res: any) => {
const firstName = res.firstName;
const lastName = res.lastName;
// const privileges = res.privileges
const privileges = ['ViewDeliverableDefinitions', 'SubmitDeliverableInstances']
this.tokenService.setPrivileges(privileges)
console.log('observable')
return Observable.create(observer => {
console.log('this is 1')
this.permissionsService.loadPermissions(privileges, () => {
console.log('this is 2')
// observer.next({
// type: 'string'
// });
this.store.dispatch(new LoginActions.LoginSuccessAction({user: res}))
// return observer.complete();
})
})
})
.catch( (e:any) => {
this.store.dispatch(new LoginActions.LoginFailureAction(true));
return Observable.create(observer => {
return observer.complete();
})
});
});
但是, Observer.create
不會調用任何東西。 我究竟做錯了什么?
有幾件事需要更新。 switchMap
,第一個map
必須是switchMap
。 這是因為Effect
必須返回發出Action
的Observable
。 這樣做將導致內部觀察對象被訂閱。 其次,Effect將為您執行此操作,而不是手動分派操作,因此您只需在每個創建的可觀察對象中發出一個新操作。
更新的代碼(減去注釋):
@Effect() /* sends request to httpService with params as login credentials on instance of loginAction. */
login$: Observable<Action> = this.actions$
.instanceOf(LoginActions.LoginAction)
.switchMap(
action => {
return this.loginHttpService.login(action.payload)
.switchMap((res: any) => {
const firstName = res.firstName;
const lastName = res.lastName;
const privileges = ['ViewDeliverableDefinitions', 'SubmitDeliverableInstances'];
this.tokenService.setPrivileges(privileges);
return new Observable<Action>(observer => {
this.permissionsService.loadPermissions(privileges, () => {
observer.next(new LoginActions.LoginSuccessAction({user: res}));
observer.complete();
});
});
})
.catch( (e:any) => {
return Observable.of(new LoginActions.LoginFailureAction(true));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.