首页 > 解决方案 > 当异步在这里时执行一个函数

问题描述

我使用 angular cli 6 和 angularfire2。我有这两个功能。我想在我的函数 CaptureScreen() 中执行 SaveDoc()。定义此 url 时如何执行 SaveDoc?谢谢

 public captureScreen()  {  
    var data = document.getElementById('contentToConvert'); 

    html2canvas( data ).then(canvas => {  

      var imgWidth =297;
      var pageHeight = 210;    
      var imgHeight = canvas.height * imgWidth / canvas.width;  
      var heightLeft = imgHeight;  
      const contentDataURL = canvas.toDataURL('image/png')  
      var doc = new jspdf('l', 'mm', 'a4'); // A4 size page of PDF  
      var position = 2;  
      doc.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight);
      doc.save();
      const file = doc.output("blob");
      const Patientid = this.patientid;
      const filePath = Date.now().toString();
      const fileRef = this.storage.ref(Patientid +'/ppss/' + filePath+'.pdf');
      const task = this.storage.upload(Patientid +'/ppss/' + filePath+'.pdf', file);
      this.uploadPercent = task.percentageChanges();
      task.snapshotChanges().pipe(
      finalize(() => {
      this.downloadURL = fileRef.getDownloadURL();
      this.downloadURL.subscribe(url => this.url = url
      )
          }))
          .subscribe();
      });  
      } 

SaveDoc(){ 
    const Patientid = this.patientid;
    const name = Date.now().toString();
    const newDoc = new Doc(name, Patientid, this.url);
    console.log(this.url);
    this.docsService.CreatePpsDoc(newDoc); 
}

标签: javascriptangularasynchronous

解决方案


如果我了解您的代码和您的意图,那么:

task.snapshotChanges()
.pipe(finalize(() => {
  this.downloadURL = fileRef.getDownloadURL();
  this.downloadURL.subscribe(url => {
   // <--  Here, your actual URL is available. 
    this.url = url;.
   // --> So you may call your function here.
   this.SaveDoc();
  })
 })
).subscribe();

你只需要“等待”,调用另一个函数,让你的 downloadURL 可用,然后你可以调用你的另一个函数,因为它有一个 downloadURL 依赖项。


推荐阅读