我如何等待数据被接收,然后在Angular中执行以下代码?

问题描述 投票:0回答:1

我正在尝试从API获取数据。问题是我要等到数据存在后再执行代码。

definObj(obj){
  console.log(obj);
}
execute(){
  this.service.getData(URL).subscribe(data => this.customerArr = data);
  this.defineObj(this.customerArr); // Workaround 
...
}

在我的service.ts中

getData(URL){
   return this.http.get(URL);
}

我希望在不使用我的解决方法的情况下定义对象。我希望程序等待接收到数据。当您更改页面时,可以使用解析器,但在这里我只想获取一些数据,而同时保持在同一页面上。

angular typescript api get
1个回答
0
投票

这是订阅的原因。取决于this.customerArr的任何工作流程都应在订阅中。

execute() {
  this.service.getData(URL).subscribe(
    data => {
      this.customerArr = data);
      this.defineObj(this.customerArr);
      ...
    },
    error => { // always good practice to handle HTTP errors }
  );
}

请参阅此处以获取有关如何访问异步数据的更多信息:https://stackoverflow.com/a/14220323/6513921

© www.soinside.com 2019 - 2024. All rights reserved.