【问题标题】:How can I run a function after a get method completes fetching information in Angular?get 方法在 Angular 中完成获取信息后如何运行函数?
【发布时间】:2019-02-27 14:48:36
【问题描述】:

我有一个从我的 mongodb 获取数据的 get 函数。 GET 函数需要几秒钟才能运行。同时,应该下一个运行并处理获取的对象数组的函数不会等待数组并运行给出错误。 一旦我的 GET 函数完成执行,有什么方法可以运行该函数?

当我点击页面上的下载按钮时,downloadVMclicked 就会运行。

downloadVMclicked(ctype){
     console.log("ctype ="+ctype)
     var vms= new Array<VM>();
     vms=[]
    this.clusters.forEach(element => {
      if(element.ctype==ctype)
      {
        this.inventoryService.getVMdownload(element.cname).subscribe(vmD =>{
          console.log("Concating this.vms "+vms+" vmDownload "+vmD)
          vms=vms.concat(vmD)
          console.log("vms length is"+vms.length)
          if(vms!=null)
          {
            console.log("VM downloaded for "+element.cname)
            console.log(vms)
          } 
          else
            console.log("VM not downloaded for "+element.cname)
        })
      }
    })
    this.download(vms);
   }

download(array){    
    console.log("Downloading "+ array.length+" items")
    var csvData = this.ConvertToCSV(array);
    var time = new Date();
    var a = document.createElement("a");
    a.setAttribute('style', 'display:none;');
    document.body.appendChild(a);
    var blob = new Blob([csvData], { type: 'text/csv' });
    var url= window.URL.createObjectURL(blob);
    a.href = url;
    a.download = 'vmAll '+time.toString()+'.csv';/* your file name*/
    a.click();
    return 'success';
   }

【问题讨论】:

标签: angular asynchronous get


【解决方案1】:

检查结果是否已经到达,如果是,则创建一个新的promise并用结果完成它。

httpGet(url) {
    if(result === undefined) {
      return this.http.get(url).toPromise().then(
          result => this.result = result.json(),
          error => console.log(error);
      );
    } else {
      return new Promise().resolve(result);
    }
}

【讨论】:

  • 我对 Angular 还很陌生,之前没有使用过 Promise。我在 Angular.io 上找不到任何关于 Promises 的信息。有没有其他网站可以找到相关信息?
  • 有很多博客和帖子,你可以查看“medium”,也可以genuitec.com/angular-observables-and-promises你可以找到更多关于 observables/proimise 的细节
  • 您好,我对您发布的代码有疑问。如果结果未定义,那么您要将结果更改为 JSON?你能解释一下你的代码吗? - @T.Shashwat
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-14
相关资源
最近更新 更多