2017-08-29 47 views
1

我试图在应用程序中使用Ionic Native QR Scanner。由于我需要多个模块中的扫描仪,我认为建立一个简单的服务可以打开扫描仪并返回结果是一个好主意。等待服务本身依赖于嵌套的promise/observables

首先,我用上面的链接提供的示例代码:

// inside qrScannerService... 
public scanQR(): Promise<void> { 
    return this.qrScanner.prepare() 
     .then((status: QRScannerStatus) => { 
      if (status.authorized) { 
       let scanSub = this.qrScanner.scan().subscribe((qrResult: string) => { 

        this.qrScanner.hide(); 
        scanSub.unsubscribe(); 
        // this is what I want, ultimately. 
        return qrResult; 
       }); 
       this.qrScanner.show(); 
      } else if (status.denied) { 
       console.log("denied"); 
      } else { 
       // permission was denied, but not permanently. 
      } 
     }) 
     .catch((e: any) => console.log('Error is', e)); 
} 

所以这就是该服务。在我的模块,我用扫描仪服务,像这样:

private doQRScan() { 
    this.qrScannerService.scanQR().then(result => { 
     console.log(result); 
    });  
} 

所以我有一个承诺链doQRScan() - >scanQR() - >prepare() - >scan(),我需要等待所有三个承诺/观测,或我需要重新调整服务方法,但对于Angular来说我是相当新的,到目前为止,答案并没有解决。

现在,prepare()返回其承诺和doQRScan()得到满足,所以实际的QR扫描从不返回。

任何想法?

回答

2

您需要在您的scanQR函数中返回一个新的承诺。我没有测试过,但这样的事情应该为你工作:

public scanQR() { 
return new Promise((resolve, reject) => { 
    this.qrScanner.prepare() 
     .then((status: QRScannerStatus) => { 
      if (status.authorized) { 
       let scanSub = this.qrScanner.scan().subscribe((qrResult: string) => { 

        this.qrScanner.hide(); 
        scanSub.unsubscribe(); 
        // this is what I want, ultimately. 
        // return qrResult; 
        resolve(qrResult) //-------> resolving your top level promise 
       }); 
       this.qrScanner.show(); 
      } else if (status.denied) { 
       console.log("denied"); 
       reject("denied!") 
      } else { 
       // permission was denied, but not permanently. 
       reject("denied!") 
      } 
     }) 
     .catch((e: any) => 
      console.log('Error is', e) 
      reject(e) 
     ); 
}) 

}