typescript 将订阅响应传递给变量-Angular

ldfqzlk8  于 2022-12-30  发布在  TypeScript
关注(0)|答案(2)|浏览(152)

我尝试将我的Http.Get的订阅响应传递给变量,但每次都是这样,每次都是 undefined

TesteToken() : any {
let token;
this.http.get<any>(`${this.url}/token`).subscribe(res => {
  token = res;
  return token;
});}

但是当我把这个

TesteToken() : any {
let token;
this.http.get<any>(`${this.url}/token`).subscribe(res => {
  token = res;
  console.log(token);
});}

然后工作,输出在控制台中

bihw5rsg

bihw5rsg1#

您可以使用以下解决方案(将observable转换为promise并添加async/await):

async TesteToken(): Promise<Something> {
    return this.http.get<any>(`${this.url}/token`).toPromise();
}

let token = await  this.TesteToken();
ccrfmcuu

ccrfmcuu2#

问题:您试图返回异步响应,就像返回同步响应一样。

TesteToken() : any { // this does not return anything since function ends before a value is returned.
    let token;
    this.http.get<any>(`${this.url}/token`).subscribe(res => {
      token = res;
      return token;  // does nothing
    });
}

修复:订阅要设置值的位置。

TestToken() : Observable<any> { // you can set the type of any
return this.http.get<any>(`${this.url}/token`);
}

访问该值;

// code runs
    this.TestToken().Subscribe((value) => { 
// code runs after value has returned from server
console.log(value); 
})
// code outside subscribe runs first without waiting.

相关问题