Ionic如何从提供商那里获得Promise Reponse?

时间:2019-02-04 11:57:35

标签: angular ionic-framework promise

因此,我试图从提供程序中的Promise中获得答复,但运气不佳。

我的组件从未收到响应,

this.printerService.print(template).then(

            response => {

              console.log(response);

            }, err => {

             console.log(err);
        });

我的提供者返回true,

print(template): Promise<any> {
  return window.cordova.plugin.zebraprinter.print(address, join,
        function(success) { 

         return true;

        }, function(fail) { 

          return false;
        }
      );
}

2 个答案:

答案 0 :(得分:2)

您没有返回您想要的承诺。

print(template): Promise<bool> {
    return new Promise(resolve => {
        window.cordova.plugin.zebraprinter.print(address, join,
            success => resolve(true), // invokes .then() with true
            fail => resolve(false) // invokes .then() with false
        );
    });
}

exampleCall() {
    this.printerService.print(template).then(answer => console.log(answer));
}

如果您希望诺言失败,可以使用reject参数。

print(template): Promise<void> {
    return new Promise((resolve, reject) => {
        window.cordova.plugin.zebraprinter.print(address, join,
            success => resolve(), // invokes .then() without a value
            fail => reject() // invokes .catch() without a value
        );
    });
}

exampleCall() {
    this.printerService.print(template)
        .then(() => console.log('success'))
        .catch(() => console.log('fail'));
}

答案 1 :(得分:0)

一种简单的方法是将zebraprinter函数包装在一个Promise中,如下所示:

print(template): Promise<any> {
   return new Promise((resolve,reject)=> {
      window.cordova.plugin.zebraprinter.print(address, join,
       (success) =>  { 

         resolve(success)

        },(fail) => { 

          reject(fail)
        }
      );
   });
}