angular - 处理异步 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 类型,而不是可观察的,所以它不起作用。
先感谢您。
对于那些感兴趣的人,这是Effect
UpdateDashboardConfiguration 操作。
@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))),
);
}
),
);
解决方案
听起来您需要修改注销功能正在执行的操作。如果您有执行操作的所需顺序,则不应让它们异步运行。
由于您使用的是 NgRx,因此您应该调度LogoutClicked
操作而不是调用服务函数。这将允许您控制流程,以便您可以按正确的顺序处理所有内容。您可以设置一个处理LogoutClicked
和调度UpdateDashboardConfiguration
动作的效果。然后,当您处理时,UpdateDashboardConfigurationSuccess
您可以决定是否需要分派一个ClearDashboardState
操作,然后您最终可以从那里分派一个Logout
调用您的注销服务功能的操作。
您可能需要更新您的操作中包含的有效负载,以帮助效果决定接下来要分派哪些操作。您可以使用此处找到的基于内容的判定器效果模式。
推荐阅读
- node.js - 如何删除 gatsby-starter-portfolio-cara 文件?
- javascript - 在角度 html 模板中显示来自ngrx 存储的单个对象
- javascript - 如何在js中更漂亮地将对象数组保持在一行
- amazon-dynamodb - 在 DynamoDB 中查询最近 7 天的数据
- javascript - 扩展运算符在 javascript 中无法正常工作
- apache-spark - 如果我运行此代码,为什么 spark 会返回“任务不可序列化”?
- kubernetes - Kubernetes - 同一命名空间中的两个不同 Pod 之间的 HTTP 通信
- android-studio-4.1 - Android Studio 中的“创建新项目”消失了
- android - 如何使用 GPS 在我的 android 应用程序中获取当前位置..?
- javascript - HTML