我正在开发一个以 REST API 作为后端的 Angular SPA 应用程序。我使用 httponly cookie JWT 令牌,并有一个拦截器在令牌过期时处理令牌刷新周期。问题是我的实现过于依赖顺序编码,而不是用 observables 解决所有问题。
private handle401Error(request: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> | Observable<never> {
if(!this.isRefreshing$.value) {
this.isRefreshing$.next(true);
return this.authenticationService.isUserLoggedIn$.pipe(
takeUntil(this.isRefreshing$.pipe(filter(isRefreshing => !isRefreshing))),
switchMap(isLoggedIn => {
if(isLoggedIn){
return this.authenticationService.refreshToken().pipe(
switchMap(() => {
this.isRefreshing$.next(false);
return next.handle(request);
}),
catchError((error) => {
if (error.status == '403' || error.status == '400') {
this.store.dispatch(LoginActions.falseLogout());
}
this.isRefreshing$.next(false);
return throwError(() => error);
})
)
} else {
return NEVER;
}
})
)
}
return this.isRefreshing$.pipe(
withLatestFrom(this.authenticationService.isUserLoggedIn$),
skipWhile(([isRefreshing,isLoggedIn]) => isRefreshing),
take(1),
switchMap(([isRefreshing,isLoggedIn]) => {
if(isLoggedIn) {
return next.handle(request)
} else {
return NEVER;
}
})
)}
handle401Error 函数的第一部分创建一个“刷新周期”,其中应用程序尝试刷新令牌,如果成功,它会重新向服务器发送请求。第二部分,在刷新令牌时对所有向后端发出的后续请求进行排队。
代码按原样运行,但我知道它可以用适当的“RxJs”方式表达,而不必在函数开头制作 if 语句。我一直无法找到提到的“RxJs”方式......是否可以按照我的建议进行?还是我已经拥有的一个好的解决方案?