Vasanth
Vasanth

Reputation: 607

Ionic 2: calling function after xhr.onload

In ionic 2, I'm using below code to upload the file(.pdf and .doc extension) into server via API. But I'm not able to call any function after resp.success == 1 or not able to use any global variables.I'm getting error like property doesn't exist on type xmlhttpeventtarget As I want to navigate user to next page on successful submission of the file I need call some function inside success.

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

Upvotes: 0

Views: 1376

Answers (2)

sebaferreras
sebaferreras

Reputation: 44669

A better way to solve this would be by using arrow functions like this:

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

Notice that now we do

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

instead of

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

By using arrow functions, the this property is not overwritten and still references the component instance (otherwise, the this keyword points to the inner function, and your custom method and variable are not defined in it).

Upvotes: 3

Vasanth
Vasanth

Reputation: 607

Hi I found solution to this problem.By creating a variable which has this reference, the snippet is as below.

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

Upvotes: 0

Related Questions