我有以下两个职能:
refreshAccessToken() {
let rt = this.injector.get(LocalStorageService);
var tokenData = rt.getAuthorizationData();
var refreshToken = tokenData.refresh_token;
var refreshToken = localStorage.getItem('userRefreshToken');
if (refreshToken !== null) {
var data = "grant_type=refresh_token&refresh_token=" + refreshToken;
var basicAuth = btoa("crmClient1:crmSuperSecret");
var headerData = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic " + basicAuth,
"No-Auth": "True",
'Access-Control-Allow-Origin': '*'
};
var reqHeader = new HttpHeaders(headerData);
this.http.post(this.tokenUrl, data, {
headers: reqHeader
})
.subscribe((response: any) => {
this.localStorageService.setAuthorizationData(response);
console.log("I need to be called first");
});
} else {
return null;
}
}
getNewAccessToken(): Observable < string > {
this.refreshAccessToken();
console.log("I need to be called as a second value");
var varTokenData = this.localStorageService.getAuthorizationData();
var newAccessToken = varTokenData.access_token;
this.newat = newAccessToken;
return of(this.newat);
}
我在getNewAccessToken()
函数中调用refreshAccessToken()
函数。在这里,代码运行良好,除了代码:
console.log("I need to be called as a second value");
var varTokenData = this.localStorageService.getAuthorizationData();
var newAccessToken = varTokenData.access_token;
this.newat = newAccessToken;
return of(this.newat);
在函数refreshAccessToken()
执行完毕之前执行。如何使其他代码等待执行,直到refreshAccessToken()
函数在角6中执行完毕?
我得到的错误如下:
AuthInterceptor的部分,我从那里调用getNewAccessToken()函数,如下所示:
//从refresh_token生成新令牌
handle401Error(req: HttpRequest<any>, next: HttpHandler) {
console.log("Error 401 called");
if (!this.isRefreshingToken) {
this.isRefreshingToken = true;
// Reset here so that the following requests wait until the token
// comes back from the refreshToken call.
this.tokenSubject.next(null);
return this.loginService.getNewAccessToken()
.pipe(
switchMap((newToken: string) => {
if (newToken) {
this.tokenSubject.next(newToken);
//this.isRefreshingToken=false;
return next.handle(this.addToken(req, newToken));
}
// If we don't get a new token, we are in trouble so logout.
//this.isRefreshingToken=false;
return this.logout();
}),
catchError(error => {
// If there is an exception calling 'refreshToken', bad news so logout.
//this.isRefreshingToken=false;
//console.log(error);
return this.logout();
})
//)
),
finalize(()=>{
this.isRefreshingToken=false;
});
} else {
return this.tokenSubject
.pipe(
filter(token => token !=null)
),
take(1),
switchMap((token: string )=> {
return next.handle(this.addToken(req,token));
});
}
}
3条答案
按热度按时间o7jaxewo1#
您可以从
refreshAccessToken
方法中执行return
和Observable
:然后从
getNewAccessToken
方法订阅它,如下所示:您可以使用ES2017中引入的
async
/await
。由于它们仅适用于处理promise
而非Observable
的函数,因此您必须稍微更改函数以返回promise
而非Observable
。具体方法如下:
然后将
getNewAccessToken
声明为async
和await
refreshAccessToken
:mwkjh3gx2#
xu3bshqb3#
如果将
Observable
对象转换为Promise
,则可以利用TypeScript的async/await模式。然后可以编写看起来更同步的代码。然而,值得指出的是,代码本身仍然使用回调和承诺来实际执行,但语法糖使其远离您。