我如何 return 来自回调函数的 ngrx / angular5 效果?

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 从未调用过任何东西。我做错了什么?

有几件事需要更新。首先 map 需要是 switchMap,如前所述。这是因为 Effect 必须 return 一个发出 ActionObservable。这样做会导致内部可观察对象被订阅。其次,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));
    });