我们在使用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回调函数的问题啦!!
是不是很简单!!!