繁体   English   中英

如何在Angular5效果中从回调返回?

[英]How can I return from a callback in an Angular5 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)
          .map( (res: any) => {
            if (res && res.message !== 'Invalid Login') {
                const firstName = res.firstName;
                const lastName = res.lastName;
                this.tokenService.setToken(res.jwt);
                this.tokenService.setFirstName(firstName.charAt(0).toUpperCase() + firstName.slice(1));
                this.tokenService.setLastName(lastName.charAt(0).toUpperCase() + lastName .slice(1));
                this.tokenService.setId(res.id);
                this.tokenService.setAvatar(firstName.charAt(0).toUpperCase() + lastName.charAt(0).toUpperCase());

                const perm = ['ADMIN']
                this.tokenService.setUserRoles(perm)
                return Observable.create(observer => {
                  this.permissionsService.loadPermissions(perm, () => {
                    observer.next({
                      type: 'string'
                    });
                    return observer.complete();

                  })
                })
            }
          }).catch( (e:any)  =>    {
          return Observable.of(new LoginActions.LoginFailureAction(true));
        });
      });

我试图从loadPermissions内部返回。 但是我得到一个错误:

Effect "LoginEffects.login$" dispatched an invalid action

如果试图退出效果而不分派动作,则需要将disaptach设置为false 您可以使用@Effect({ dispatch: false })装饰效果,然后在所有返回操作的地方都需要调用this.store.dispatch(/* Some Action */); 你自己。

@Effect({ dispatch: false })
login$: Observable<Action> = this.actions$
  .instanceOf(LoginActions.LoginAction)
  .switchMap(
    action => {
      this.loginHttpService.login(action.payload)
        .map( (res: any) => {
          if (res && res.message !== 'Invalid Login') {
            // Logic omitted
            this.permissionsService.loadPermissions(perm, () => {
             // Dispatch an action
             this.store.dispatch(new LoginActions.LoginSuccessAction(true)));
            });
          }
        }).catch( (e:any)  =>    {
          this.store.dispatch(new LoginActions.LoginFailureAction(true)));
        });
      });

constructor(private store: Store<any>) {} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM