从服务获取状态回调函数

get status callback function from service

如何在组件和服务之间实现回调函数..抱歉我对angular和打字稿还是个新手

getDiscount(){
    let getDisc = [];
    getDisc.push({
      price: Number(this.commonService.getPayments$.getValue())
    });
    
    this.commonService._getGlobalDiskaun(getDisc[0])
    setTimeout(() => this.getResult(),1000); 
  }

我正在尝试像上面的代码一样实现,但是当网络速度慢时它会给出空结果。 this.commonService._getGlobalDiskaun(getDisc[0]) 获取值然后调用此函数时如何编码 this.getResult()

出现此问题是因为您正在使用延迟 1 秒的 setTimeout 方法,而 API 的结果可能不会在一秒内到达 您需要 subscribe 您正在使用的服务,以便您可以在收到 API 的响应后立即调用该函数,如下所示:

this.commonService._getGlobalDiskaun(getDisc[0]).subscribe(result => this.getResult())

您还需要 return 服务中的数据,如下所示:

_getGlobalDiskaun(){
   return this.http.get<any>(`${your_api_address}`)
}

这可能是一个 POST 请求,但没关系,您仍然需要 return 您的服务中的响应