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回調函數的問題啦!!

是不是很簡單!!!



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章