首页 > 解决方案 > rxjs地图操作员在switchMap之后没有在管道中触发

问题描述

当谈到 rxjs 时,我认为自己非常精明,但我无法弄清楚我做错了什么。我正在尝试通过将我的用户登录转换为效果来学习 ngrx。我的效果正确触发,并且从我的服务器返回了正确的令牌响应(通过登录控制台验证),但地图操作员从未在我的效果中被触发。

这是我的效果代码:

@Injectable()
export class UserEffects {

constructor(
    private authService: AuthService,
    private actions$: Actions
) { }

    @Effect() loginUser$ = this.actions$
    .ofType<userActions.LoginUserAction>(userActions.LOGIN_USER).pipe(
        switchMap(action => this.authService.Login(action.payload)),
        map(user => (new userActions.LoginUserSuccessAction(user)))
    );
}

以及我的服务层中的请求:

public Login(model: ILogin) {
return this.http.post<string>(`${baseUrl}api/login`, model).pipe(
  // Returns the object to be stored in AppState
  map(response => this.GetTokenInformation(response))
);

}

我曾尝试使用 flatMap 和 mergeMap 以防我在 ngrx 文档中遗漏了某些内容,但这些都不起作用。

我的运营商正在像这样被导入:

import { map, switchMap } from 'rxjs/operators';

让我知道我是否可以提供其他任何东西...谢谢!

标签: angularrxjsngrxngrx-effectsswitchmap

解决方案


尝试使用这样的东西: 来自示例应用程序的登录效果

loginUser$ = this.actions$.pipe(
  ofType<userActions.LoginUserAction>(userActions.LOGIN_USER),
  map(action => action.payload),
  exhaustMap((auth: any) =>
    this.authService
      .Login(auth)
      .pipe(
        map(user => (new userActions.LoginUserSuccessAction(user)))
      )
  )
);

switchMap 将重置效果,但 exhaustMap 等到内部 observable 完成。

搜索更多关于这两个运算符的差异


推荐阅读