2017-08-29 7 views
1

Ionic Native QR Scannerをアプリケーションで使用しようとしています。スキャナが複数のモジュールで必要になるので、スキャナを開いて結果を返すことができる簡単なサービスを構築することをお勧めします。だから、サービスのネストされた約束/オブザーバに依存するサービスを待っています

// 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)); 
} 

:で開始する

、私は上記のリンクで使用可能なサンプルコードを使用しています。 - >scanQR() - >prepare() -

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

だから私は約束チェーンdoQRScan()持っている>scan()を、私はすべての3つの約束/観測に待機する必要があり、または:私のモジュールでは、私はそうは次のようにスキャナサービスを使用します私はサービス方法を再構成する必要がありますが、私はかなり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) 
     ); 
}) 

}

関連する問題