我有两个功能,如下所示:
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);
}
我正在refreshAccessToken()
函数内调用getNewAccessToken()
函数。在这里,除以下代码外,代码运行良好:
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中完全执行?
我得到的错误如下:
我从中调用getNewAccessToken()函数的AuthInterceptor部分如下:
///从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));
});
}
}
答案 0 :(得分:0)
您可以通过return
方法Observable
refreshAccessToken
:
import { of } from 'rxjs';
import { tap } from 'rxjs/operators';
refreshAccessToken(): Observable<any> {
...
if (refreshToken !== null) {
...
return this.http.post(this.tokenUrl, data, {
headers: reqHeader
})
.pipe(tap(response => this.localStorageService.setAuthorizationData(response)));
} else {
return of(null);
}
}
然后从您的getNewAccessToken
方法进行订阅,如下所示:
getNewAccessToken(): Observable<string> {
this.refreshAccessToken()
.subscribe(response => {
...
});
}
或者:
您可以使用ES2017中引入的async
/ await
。由于它们仅与处理promise
而不是Observable
的函数一起使用,因此您将不得不稍微更改函数以返回promise
而不是Observable
。
方法如下:
import { of } from 'rxjs';
import { tap } from 'rxjs/operators';
refreshAccessToken() {
...
if (refreshToken !== null) {
...
return this.http.post(this.tokenUrl, data, {
headers: reqHeader
})
.pipe(tap(response => this.localStorageService.setAuthorizationData(response)))
.toPromise();
} else {
return of(null).toPromise();
}
}
然后将getNewAccessToken
声明为async
和await
refreshAccessToken
:
async getNewAccessToken() {
await this.refreshAccessToken();
...
}
答案 1 :(得分:0)
如果将Observable
对象转换为Promise
,则可以利用TypeScript的async/await模式。然后,您可以编写看起来更同步的代码。值得一提的是,代码本身仍在使用回调和Promises来实际执行,但这是通过语法糖从您那里抽象出来的。
async getNewAccessToken(): Promise<string> {
// Your refreshAccessToken() needs to always return an Observable now.
await this.refreshAccessToken().toPromise();
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 this.newat;
}
答案 2 :(得分:0)
import { forkJoin } from "rxjs";
async ngOnInit() {
await this.getDataFromMultipleApis().then(data=>{
console.log(data);
});
}
getDataFromMultipleApis(){
return new Promise((res, rej) => {
forkJoin(
this.Service.api1(),
this.Service.api2()
).subscribe(docs => {
res(docs);
});
});
}