【问题标题】:Angular 9. Retry the function after re-authorization and with a new sessionAngular 9. 重新授权并使用新会话重试该功能
【发布时间】:2026-02-13 01:35:02
【问题描述】:

我有一个接收数据的函数

getAll(params) {
  return this.http.get(url).pipe(map(data => {
    return data
  })
})

在 this.http.get 中,我使用会话 ID 进行身份验证。如果我的会话终止,我如何使用发布请求调用重新登录函数并重试我的 getAll()

【问题讨论】:

  • 这完全取决于您的架构。您应该提供堆栈闪电战代码或提供更可靠的问题描述。

标签: javascript angular ionic-framework rxjs


【解决方案1】:

我认为您参考了刷新令牌方法。试试这个链接https://jasonwatmore.com/post/2020/05/22/angular-9-jwt-authentication-with-refresh-tokens 但你应该使用 OAuth2 或类似的隐式流。

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
    constructor(private authenticationService: AuthenticationService) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(err => {
            if ([401, 403].includes(err.status) && this.authenticationService.userValue) {
                // auto logout if 401 or 403 response returned from api
                // this.authenticationService.logout();
                // Or call your get token and try it again
            }

            const error = (err && err.error && err.error.message) || err.statusText;
            console.error(err);
            return throwError(error);
        }))
    }
}

【讨论】: