我是使用angular的订阅制作http请求的新手,所以我不知道是否有可能(但我用promises做了一次) 我在我的nativescript应用程序中使用带有我自己的拦截器的角度HttpClient,我在其中添加了https://angular.io/guide/http#intercepting-all-requests-or-responses
之类的Authorization标头我获得的令牌在25分钟后到期,因此我会抓住401响应,发出新的登录请求并使用新令牌再次重试原始请求。
所以我做了一些这样的想法(不工作):
...
next.handle(newRequest)
.catch((response: HttpErrorResponse) => {
if (response.status === 401) {
return next.handle(new HttpRequest("POST", loginUrl, credentials))
.subscribe((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
BackendService.token = event.body.token;
return next.handle(newRequest).subscribe();
}
})
);
}
return Observable.throw(response);
})
我意识到它曾经使用承诺(在自定义服务中),如:
request.catch((response: HttpErrorResponse) => {
if(response.status === 401) {
return http.post(loginUrl, credentials)
.then(response => {
return requestWithNewToken;
}, error => {
... redirect UI to login -> login with saved credentials failed
})
}
})
我想通过提供服务的拦截器处理这一切。