角度订阅。无法获取数据

cbl*_*793 3 api service typescript angular

更新 我是如何做到的(滚动到我的答案或这里是链接):https : //stackoverflow.com/a/55013081/1729405

我正在尝试在 Angular 7 中构建一个 APIService。我正在使用 subscribe 来推送到一个我无法通过其他服务访问的数组。

下面是api服务方法:

  getResponse(url):Observable<any> {
    return this.http.post(url, '', {responseType: 'text'});
  }

  getAll() {
      this.getResponse(this.todayApiUrl).subscribe(
        (response) => {
          this.data.push(response);
        });

      return this.data;
  }
Run Code Online (Sandbox Code Playgroud)

这是我尝试在辅助服务中调用它的方式:

export class AdsHealthService {
  today = this.callResponseApiService.getAll();


  constructor(private callResponseApiService: CallResponseApiService) { }

  getHealthValue(interval, type) {
    let obj = this.today;
    console.log(obj);
  }
}
Run Code Online (Sandbox Code Playgroud)

在附加的图像中是我得到console.log()的回应。它看起来像一个数组,但是当我尝试访问第一个元素时,我收到一条undefined消息。我究竟做错了什么?? 在此处输入图片说明

Jos*_*tič 5

这是因为http.post是异步的,你可以把它同步通过使getResponse() async,改造Observable,以Promise通过.toPromise()并添加await之前http.post,因为这将getResponse()不会返回可观察到,但原始数据,所以.subscribe()不再需要。

  async getResponse(url) {
    return await this.http.post(url, '', {responseType: 'text'}).toPromise();
  }

  async getAll() {
    this.data = await this.getResponse('some url');
    return this.data
  }
  async some() {
    const data = await this.getAll();
    console.log(data);
    console.log(this.data);
  }
Run Code Online (Sandbox Code Playgroud)