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

问题描述 投票:0回答:1
  @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
angular rxjs ngrx ngrx-effects
1个回答
1
投票

如果您试图在不调度动作的情况下退出效果,则需要将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>) {} 
© www.soinside.com 2019 - 2024. All rights reserved.