【问题标题】:Ionic how to get a Promise Reponse from a provider?离子如何从提供者那里获得承诺响应?
【发布时间】:2019-02-08 08:14:03
【问题描述】:

所以我试图从 Provider 的 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;
        }
      );
}

【问题讨论】:

    标签: angular ionic-framework promise


    【解决方案1】:

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

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

    如果你想让 promise 失败,你可以使用 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'));
    }
    

    【讨论】:

      【解决方案2】:

      实现这一点的一种简单方法是将 zebraprinter 函数包装在一个 promise 中,如下所示:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-22
        • 2020-08-05
        • 2022-11-07
        • 2021-11-05
        • 2020-09-12
        • 2016-01-06
        • 1970-01-01
        相关资源
        最近更新 更多