如何在NgRx Effect中调用多服务?登录后执行产品服务并返回成功动作
解决方案:登录成功后调用产品服务并存储数据
你可以通过在登录请求的成功回调中链式调用产品服务,完成数据存储后再返回登录成功动作,具体修改如下:
修改后的LoginEffects代码
@Injectable() export class LoginEffects { login$ = createEffect(() => this.actions$.pipe( ofType(login), exhaustMap((action) => this.loginService .login({ username: action.credentials.username, password: action.credentials.password, }) .pipe( // 用concatMap替代map,实现登录成功后链式调用产品服务 concatMap((userModel) => this.productService.findAll().pipe( tap((products) => { // 将产品数据存入sessionStorage sessionStorage.setItem('products', JSON.stringify(products)); // 执行登录成功后的提示与页面跳转 this.matSnackBar.open('some message'); this.router.navigateByUrl('/admin/dashboard').then(); }), // 最终返回登录成功动作,维持原有状态更新逻辑 map(() => successfulLogin({ userModel })) ) ), catchError(() => { this.matSnackBar.open( this.translateService.instant('shared.error-message') ); return EMPTY; }) ) ) ) ); constructor( private readonly translateService: TranslateService, private readonly productService: ProductService, private readonly loginService: LoginService, private readonly matSnackBar: MatSnackBar, private readonly actions$: Actions, private readonly router: Router ) {} }
关键说明
- 使用
concatMap:确保登录请求完全成功后再发起产品服务请求,避免异步操作顺序混乱 tap操作符:专门处理存储数据、提示、页面跳转等副作用逻辑,不干扰数据流本身- 保留返回
successfulLogin动作:保证NgRx Store能正常更新登录状态,不破坏原有业务流程
内容的提问来源于stack exchange,提问作者Mario
相关产品推荐
相关产品推荐

