angular - 在拦截器中订阅时没有任何反应
问题描述
我想刷新一个令牌,但是当 api 调用完成时,令牌没有刷新,我看不到它里面的日志。在这里我设置了一个超时去快速测试刷新然后重试使用令牌请求但没有任何反应。它应该在到期前添加时间。
if (token) {
authReq = req.clone({
headers: req.headers.set(TOKEN_HEADER_KEY, 'Bearer ' + token),
});
const jwtToken = JSON.parse(atob(token.split('.')[1]));
const expires = new Date(jwtToken.exp * 1000);
console.log(expires);
const timeout = expires.getTime() - Date.now() - 100 * 1000;
console.log('time', timeout);
if (timeout >= 0 && timeout <= 19000) {
this.http
.post<any>(environment.apiBaseUrl + 'refresh', authReq.headers)
.pipe(
switchMap((d) => {
//can't see its content
console.log(d);
authReq = req.clone({
headers: req.headers.set(TOKEN_HEADER_KEY, 'Bearer ' + token),
});
console.log('after: ', expires);
return next.handle(authReq);
})
);
}
}
解决方案
您需要像这样返回http请求。
return this.http
.post<any>(environment.apiBaseUrl + 'refresh', authReq.headers)
.pipe(
这将导致请求触发。您的控制台日志根本没有触发的原因是没有触发 http 请求。
还使用map()
. 你不需要一个switchMap()
推荐阅读
- azure - Azure SQL 数据库有时连接缓慢
- java - Soapmessage 添加命名空间
- c++ - 没有显示视频 (GUI) 时,是否可以允许与 MPV C API 进行键绑定?
- java - 超级缩减字符串:我的代码有问题 - Java
- r - 为每条边查找间接节点(在 R 中)
- git - 如何从 Github 历史记录中删除本地不存在的提交?
- sql - posgresql json_agg 里面的 json_agg
- javascript - 如何使用 alpine.js 复制表单
- roblox - 我的变量值不会在我的脚本上更新
- python - 'tuple' 对象没有属性 'random_split'