离子2:在xhr.onload之后调用函数

时间:2017-06-01 10:14:54

标签: ajax cordova ionic2

在离子2中,我使用下面的代码通过API将文件(.pdf和.doc扩展名)上传到服务器。但是我无法在 resp.success == 1 之后调用任何函数或者无法使用任何全局变量。我收到类似xmlhttpeventtarget类型属性的错误由于我想在成功提交文件时将用户导航到下一页,我需要在成功中调用一些函数。

        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);

2 个答案:

答案 0 :(得分:2)

解决此问题的更好方法是使用箭头功能,如下所示:

  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属性不会被覆盖,仍然引用组件实例(否则,this关键字指向内部函数,您的自定义方法和变量是没有定义)。

答案 1 :(得分:0)

您好我找到了解决此问题的方法。通过创建具有引用的变量,该代码段如下所示。

    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);