[英]How can I return from an effect with ngrx / angular5 from a callback function?
My effect has: 我的效果是:
@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();
})
});
});
However, nothing ever gets called from Observer.create
. 但是,
Observer.create
不会调用任何东西。 What am I doing wrong? 我究竟做错了什么?
There are a couple of things that need to be updated. 有几件事需要更新。 First
map
needs to be a switchMap
as previously suggested. switchMap
,第一个map
必须是switchMap
。 This is because an Effect
must return an Observable
that emits an Action
. 这是因为
Effect
必须返回发出Action
的Observable
。 Doing so will cause the inner observable to be subscribed to. 这样做将导致内部观察对象被订阅。 Second, instead of dispatching the action manually, the Effect will do this for you and so you need to just emit a new action in each created observable.
其次,Effect将为您执行此操作,而不是手动分派操作,因此您只需在每个创建的可观察对象中发出一个新操作。
Updated code (minus comments): 更新的代码(减去注释):
@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.