首页 > 解决方案 > 处理异步 NgRx 操作

问题描述

我有一个 Angular 应用程序,主视图分为 2 个组件。这将涉及以异步方式处理 NgRx 操作的调度。

1) MenuComponent- 这包含各种导航按钮,例如注销按钮。单击注销按钮后,它会调用authenticationService.logout(),向后端发送 http 请求,然后注销用户。因此,这是一个异步操作。

public logout() {
  this.authenticationService.logout();
  this.router.navigate(['login']);
}

2) DashboardComponent- 我编写了以下代码来处理OnDestroy生命周期钩子,每当组件被销毁时都会调用它。它使用 NgRx 进行状态管理。

ngOnDestroy() {
  this.store.dispatch(new UpdateDashboardConfiguration());
  this.store.dispatch(new ClearDashboardState());
}

调度UpdateDashboardConfiguration()操作将导致应用程序向服务器发送 http 请求以保存仪表板的配置,因此它也是异步的。

主要问题是,当用户决定通过单击 上的注销按钮注销时MenuComponent,有没有办法确保在UpdateDashboardConfiguration()调度动作之前完成调度ClearDashboardState(),以及authenticationService.logout()从其他 MenuComponent 被调用?

首选流程如下:

UpdateDashboardConfiguration=> ClearDashboardState=>logout()

对于那些想知道的人,this.store.dispatch(new UpdateDashboardConfiguration()).subscribe(...)因为 store.dispatch() 是 void 类型,而不是可观察的,所以它不起作用。

先感谢您。


对于那些感兴趣的人,这是EffectUpdateDashboardConfiguration 操作。

@Effect()
UpdateDashboardConfiguration$ = this.actions$.pipe(
  ofType<UpdateDashboardConfiguration>.(DashboardActionTypes.UpdateDashboardWidget),
  withLatestFrom(this.store.select(selectDashboardLayoutStateConfig)),
  switchMap(action => {
    return this.dashboardService.updateDashboardConfiguration(action).pipe(
      map(data => (new UpdateDashboardConfigurationSuccess(data))),
    );
  }
  ),
);

标签: angulartypescriptreduxrxjsngrx

解决方案


听起来您需要修改注销功能正在执行的操作。如果您有执行操作的所需顺序,则不应让它们异步运行。

由于您使用的是 NgRx,因此您应该调度LogoutClicked操作而不是调用服务函数。这将允许您控制流程,以便您可以按正确的顺序处理所有内容。您可以设置一个处理LogoutClicked和调度UpdateDashboardConfiguration动作的效果。然后,当您处理时,UpdateDashboardConfigurationSuccess您可以决定是否需要分派一个ClearDashboardState操作,然后您最终可以从那里分派一个Logout调用您的注销服务功能的操作。

您可能需要更新您的操作中包含的有效负载,以帮助效果决定接下来要分派哪些操作。您可以使用此处找到的基于内容的判定器效果模式。


推荐阅读