2017-06-01 77 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);