简体   繁体   中英

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));
        });
      });

I'm trying to return from inside the loadPermissions . But I get an error:

Effect "LoginEffects.login$" dispatched an invalid action

If you are trying to exit the effect without dispatching an action you need to set disaptach to false . You decorate your effect with @Effect({ dispatch: false }) and then everywhere you return an Action you need to call this.store.dispatch(/* Some Action */); yourself.

@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>) {} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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