[英]Multiple Observables sharing single Error rxjs angular
我正在嘗試使用 Oauth2 身份驗證處理 API 請求。
我有一個authService
具有三個屬性( accessToken
、 refreshToken
和refreshTokenObservable
- 稍后描述)和apiGet()
方法,它使用 Authorization 標頭創建 HTTP GET 請求,如下所示:
apiGet(cleanedPath:string) {
return this.config.getConfig().pipe(mergeMap((config: Config) => {
[...] // Cleans parameters and creates a final query string
// Adding access token as header
let headers: object = {headers: new HttpHeaders().set('Authorization', this.accessToken)}
return this.http.get<any>(cleanedPath, headers).pipe(catchError(this.handleApiGetError.bind(this, cleanedPath)));
}));
}
我希望handleApiGetError()
方法調用新的刷新令牌並嘗試重復apiGet()
,我嘗試將多個apiGet()
調用連接到單個可觀察對象,如下所示:
private handleApiGetError(cleanedPath:string, error: HttpErrorResponse) {
if (!this.refreshTokenObservable) {
// getAccessByRefreshToken() is simple HTTP post
this.refreshTokenObservable = this.getAccessByRefreshToken();
}
return this.refreshTokenObservable.pipe(mergeMap(()=> {
return this.apiGet(cleanedPath);
}));
}
但是,這不起作用,因為它在每個失敗的apiGet()
調用新令牌,導致 OAuth 服務返回多個 E401(令牌已被撤銷)。
有沒有辦法將apiGet()
觀察者綁定在一起,並且在錯誤的情況下只調用一次刷新令牌請求並重新調用失敗的apiGet()
調用?
考慮使用retryWhen
只重試一次,最重要的是反轉控制,以便您的ErrorHandler
不負責再次重試(通過調用其調用者)。
使用retryWhen
你的 HTTP 請求只會在this.handleApiGetError()
返回的 Observable 完成后重試,如下所示:
apiGet(cleanedPath: string) {
return this.config.getConfig().pipe(
mergeMap((config: Config) => {
return this.http.get<any>(cleanedPath, headers).pipe(
retryWhen(x => this.handleApiGetError())
);
})
);
}
private handleApiGetError(error: HttpErrorResponse) {
return this.refreshTokenObservable;
}
話雖如此, handleApiGetError
可能是不必要的,因為您可以直接調用getAccessByRefreshToken
,如下所示:
apiGet(cleanedPath: string) {
return this.config.getConfig().pipe(
mergeMap((config: Config) => {
return this.http.get<any>(cleanedPath, headers).pipe(
retryWhen(this.getAccessByRefreshToken)
);
})
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.