在异步函数之后运行一个函数

时间:2020-06-27 13:50:02

标签: angular angular-promise angular-httpclient

我正在与HttpClient一起使用Angular,遇到以下问题:

我具有以下功能,可从本地数据库保存金额

getAmount(){
this.httpClient.get('https://myfirebasedatabase.com/test.json').subscribe(
  (response)=>{
    this.amount = response['total'];
  },
  (error) => {
    console.log('error' + error);
  }
);
}

此功能运行良好,但是当我尝试使用变量this.amount时未定义

this.getAmount();
console.log(this.amount);     //output undefined

我尝试做this.getAmount().then ...,但是不能,因为它的类型无效。 我也尝试为getAmount创建一个Promise,但是不能在类型订阅上使用then()。

谢谢。

2 个答案:

答案 0 :(得分:2)

要与getAmount()之类的异步服务一起使用,Angular的方法是返回一个Observable,该Observable解析为要在订户中访问的值。通常的方法是不订阅服务调用,而可能需要一些额外的RxJs管道之后将其返回:

getAmount(){
return this.httpClient.get('https://myfirebasedatabase.com/test.json')
    .pipe(
        pluck('total')   // same as map(response => response.total)
     );
}

然后在使用代码中,使用subscribe代替then

this.getAmount().subscribe(total => { 
    this.amount = total;
    console.log(this.amount);
});

答案 1 :(得分:0)

您是否尝试将客户端调用包装到异步函数中,以便可以在方法的主体中等待其响应?例如。

const getAmountAsync = () => {
  return new Promise((resolve, reject) => {
        this.httpClient.get('https://myfirebasedatabase.com/test.json').subscribe(
        (response)=>{
            resolve(response['total'])
        },
        (error) => {
            reject(error)
        }
        );
})
}

//main body:

this.amount = await getAmountAsync()

相关问题