typescript 如何在执行以下代码之前等待函数在angular 6中完成其执行?

uajslkp6  于 2023-01-21  发布在  TypeScript
关注(0)|答案(3)|浏览(144)

我有以下两个职能:

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));
            });
    }
}
o7jaxewo

o7jaxewo1#

您可以从refreshAccessToken方法中执行returnObservable

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声明为asyncawaitrefreshAccessToken

async getNewAccessToken() {
  await this.refreshAccessToken();
  ...
}
mwkjh3gx

mwkjh3gx2#

import { forkJoin } from "rxjs";

async ngOnInit() {
  let data = await this.getDataFromMultipleApis();
  console.log(data);
}
getDataFromMultipleApis(){
   return new Promise((resolve, reject) => {
      forkJoin(
        this.Service.api1(),
        this.Service.api2()
      ).subscribe(docs => {        
        resolve(docs);
      });
    });
}
xu3bshqb

xu3bshqb3#

如果将Observable对象转换为Promise,则可以利用TypeScript的async/await模式。然后可以编写看起来更同步的代码。然而,值得指出的是,代码本身仍然使用回调和承诺来实际执行,但语法糖使其远离您。

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;
}

相关问题