ionic3回调函数

我们在使用ionic1 的 JavaScript回调函数的时候是这样的,代码如下:

public postdatass(parameter: string, customer: any,callback){
  var url = APP_SERVE_URL + parameter;
  // console.log('%c 请求发送前 %c', 'color:blue', 'url', url, 'customer', customer);
    this.http.post(url, customer, {
      headers: new HttpHeaders({
        "Content-Type": "application/json"
      })
    }).subscribe(res => {
      console.log('%c 请求处理成功 %c', 'color:red', 'url', url, 'res', res);
      callback(res);

    }, error => {
      console.log('%c 请求处理失败 %c', 'color:red', 'url', url, 'err', error);
      callback(error);
    });
}
然后如下这样调用
this.httpProvider.postdatas(parameter,customer,function (response) {
  console.log(response);
})
但是这样的回调方法在ionic3中已经不起作用了,如果在ionic3还使用上述的回调函数就会出现一个变量的有效范围问题。

解决办法:引入Promise来代替原来的回调函数的作用!代码如下:

public postdatas(parameter: string, customer: any){
  var url = APP_SERVE_URL + parameter;
  // console.log('%c 请求发送前 %c', 'color:blue', 'url', url, 'customer', customer);

  return new Promise((resolve, reject) => {
    this.http.post(url, customer, {
      headers: new HttpHeaders({
        "Content-Type": "application/json"
      })
    }).subscribe(res => {
      console.log('%c 请求处理成功 %c', 'color:red', 'url', url, 'res', res);
      resolve(res);

    }, error => {
      console.log('%c 请求处理失败 %c', 'color:red', 'url', url, 'err', error);
    reject(error);
}); })}
调用方法改为如下代码:
this.httpProvider.postdatas(parameter,customer).then(data=>{
  this.navCtrl.setRoot(TabsPage);
})

这样子就可以解决ionic3回调函数的问题啦!!

是不是很简单!!!



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值