2017-06-01 26 views
0

在ionic 2中,我使用下面的代碼通過API將文件(.pdf和.doc擴展名)上傳到服務器。但我無法調用resp.success == 1或無法使用任何全局變量之後調用任何函數。我得到錯誤,如屬性不存在類型xmlhttpeventtarget因爲我想導航用戶到成功提交文件的下一頁,我需要在成功內部調用一些函數。Ionic 2:xhr.onload後調用函數

 xhr.open('POST', "myurl", true); 
     xhr.onload = function() { 


     if (xhr.status == 200) { 
      var resp = JSON.parse(xhr.response); 
      console.log('Server got: in IOS ', resp); 
      console.log('Server got: in IOS ', resp.message); 

      if(resp.success == 1) 
      { 
       console.log("THIS IS SUCCESS")  

      } 
      else{ 
       alert(resp.message) 
       return 
      } 

      }; 
    } 


     xhr.send(this.fd); 
+0

哪些屬性不存在?請提供完整的錯誤堆棧跟蹤。順便說一下,如果你使用Ionic 2,爲什麼不使用Angular 2的Http Client(https://angular.io/docs/ts/latest/guide/server-communication.html)來抽象實現客戶端 - 服務器通信通過http? –

+0

嘿謝謝你的迴應,我可以通過聲明一個初始化爲這個前綴的變量來解決這個問題:var self = this;那麼我可以使用self.function_name和self.variable_name來使用所有函數和全局變量。 – Vasanth

回答

0

一個更好的辦法來解決,這將是通過使用箭頭功能這樣的:

xhr.open('POST', "myurl", true); 
    xhr.onload =() => { 

    if (xhr.status == 200) { 
     var resp = JSON.parse(xhr.response); 
     console.log('Server got: in IOS ', resp); 
     console.log('Server got: in IOS ', resp.message); 

     if(resp.success == 1) { 
      console.log("THIS IS SUCCESS"); 

      // Now 'this' points to the component :) !! 
      this.yourcustomfunction(); 
      this.yourvariableblename; 

     } else{ 
      alert(resp.message) 
      return 
     } 

     }; 
} 

xhr.send(this.fd); 

注意,現在我們做

xhr.onload =() => {...}); 

,而不是

xhr.onload = function() {...}); 

通過使用箭頭函數,this屬性不會被覆蓋,並仍然引用組件實例(否則,此關鍵字指向內部函數,並且您的自定義方法和變量未在其中定義)。

+1

是的,它的工作。感謝您的幫助。您的解決方案非常高效 – Vasanth

+0

很高興聽到:) – sebaferreras

0

您好我發現解決這個problem.By創建具有引用的變量,代碼段如下所示。

var self = this; 
    xhr.open('POST', "myurl", true); 
    xhr.onload = function() { 


    if (xhr.status == 200) { 
     var resp = JSON.parse(xhr.response); 
     console.log('Server got: in IOS ', resp); 
     console.log('Server got: in IOS ', resp.message); 

     if(resp.success == 1) 
     { 
      console.log("THIS IS SUCCESS")  
      self.yourcustomfunction() 
      self.yourvariableblename 
     } 
     else{ 
      alert(resp.message) 
      return 
     } 

     }; 
} 


    xhr.send(this.fd);