angular - 每次用户注销时都会发送一个新的重复注销 HTTP 请求:Angular、RxJs
问题描述
问题描述
首先,让我先说我在前端使用Angular 10 和 Nebular UI 库,后端 API使用Node.js ,使用电子邮件/密码策略进行身份验证的 JWT。我注意到,每次用户在不刷新应用程序的情况下登录并注销时,都会向服务器发出一个新的重复注销请求(正在发送多个 http 请求)。 但是,如果您在退出后刷新应用程序,问题就会消失. 我不确定我是否跳过了某些内容,或者我只是不知道使用 JWT 注销并重新登录的正确方法,但是我几天来一直试图找到解决这个问题的方法,但没有成功所以我渴望得到一些帮助。
当前行为:
如果用户多次登录并再次注销,则向服务器发出的注销请求将重复。无论您是否使用 http 拦截器(NbAuthJWTInterceptor 或其他),此问题仍然存在。
预期行为:
如果用户要重新登录并重新注销,则无论用户在不刷新应用程序的情况下重复这些步骤多少次,都不应向服务器发出多余的注销请求。
重现步骤:
- 用户第一次登录时一切正常,并且在您注销时没有向服务器发出重复的请求。
- 在您第 2 次重新登录和第 2 次退出后没有刷新应用程序,您向服务器发出的第 2 次退出请求将发送重复的退出请求(2 个相同的退出请求被发送到服务器)。
- 如果用户第 3 次再次登录并第 3 次退出,则将向服务器发送 3 个注销请求(总共发出 3 个相同的请求)。
- 如果用户要重新登录并重新注销,则将再次发送一次注销请求,并且总共会发送 4 个相同的注销请求。这种情况无限期地持续下去。
这是我的开发工具网络选项卡中这 4 个步骤的屏幕截图(在登录和退出 4 次之后):
相关代码: 在客户端,我有header.component.ts文件,从中启动注销过程:
...
ngOnInit() {
// Context Menu Event Handler.
this.menuService.onItemClick().pipe(
filter(({ tag }) => tag === 'my-context-menu'),
map(({ item: { title } }) => title),
).subscribe((title) => {
// Check if the Logout menu item was clicked.
if (title == 'Log out') {
// Logout the user.
this.authService.logout('email').subscribe(() => {
// Clear the token.
this.tokenService.clear()
// Navigate to the login page.
return this.router.navigate([`/auth/login`]);
});
}
if (title == 'Profile') {
return this.router.navigate([`/pages/profile/${this.user["_id"]}`]);
}
});
}
...
在服务器端,有一个返回成功 200 响应的注销 API 路由:
// Asynchronous POST request to logout the user.
router.post('/sign-out', async (req, res) => {
return res.status(200).send();
});
解决方案
您正在订阅另一个订阅。这会导致每次this.menuService.onItemClick()
调用时都进行另一个订阅。
您需要通过使用适当的 Rxjs 运算符(exhaustMap、concatMap、switchMap、mergeMap)来使用扁平化策略。
在您的情况下,我会像这样重构(不要忘记取消订阅ngOnDestroy中的每个订阅)
const titleChange$ = this.menuService.onItemClick()
.pipe(
filter(({ tag }) => tag === 'my-context-menu'),
map(({ item: { title } }) => title)
);
this.logOutSubscription = titleChange$.pipe(
filter((title) => title == 'Log out'),
exhaustMap((title) => this.authService.logout('email')),
tap(() => {
this.tokenService.clear()
this.router.navigate([`/auth/login`]);
})
.subscribe();
this.profileNavSubscription = titleChange$
.pipe(
filter((title) => title == 'Profile'),
tap(title => {
this.router.navigate([`/pages/profile/${this.user["_id"]}`])
})
.subscribe();
`
推荐阅读
- java - Android 开放图谱
- javascript - 哪个更大?!我的 js 代码中的一个问题
- python - 如何根据第三个有条件地组合两列
- php - Laravel 管理员更新用户信息,更新自己的管理员帐户信息时重复的电子邮件条目
- python - 从第一个元素是索引的二维数组中获取索引
- node.js - Mongodb聚合不同的唯一和排序
- c - 为什么 for 忽略 if 语句?
- android - MQTT Paho 客户端不会自动重新连接到代理
- next.js - Next-auth Package subpath '.providers/...' 不是由“exports”定义的
- javascript - facebook 如何检测 webview 或嵌入式浏览器