Search code examples
javascriptangularjsxmlhttprequest

JavaScript getting variable outside xhr function using angular 2


I am trying to get the variable that was initialized before the constructor. For example

title: String = 'hello'

To get that from a function( this works)

functionname () {
    //this will work
    console.log(this.title)
}

But from my original code, i am trying to get it from XHR's onload function and not able to access it.

export class UploadComponent implements OnInit {
  description: string;
  title: string;

  constructor() {
  }

  ngOnInit() {
  }

  upload() {
    this.makeFileRequest("/api/upload_video", []).then((result) => {
      console.log(result);
    }, (error) => {
      console.error(error);
    });
  }

  makeFileRequest(url: string, params: Array<string>) {
    return new Promise((resolve, reject) => {
      var formData: any = new FormData();
      var xhr = new XMLHttpRequest();

      xhr.open("POST", url, true);
      xhr.responseType = 'text';

      xhr.onload = function () {
        if (xhr.readyState === xhr.DONE) {
          //trying to get this.title
          console.log(this.title)
        }
      };
      xhr.send(formData);
    });
  }
}

error

'Error' message: 'Property 'title' does not exist on type XMLHttpRequestEventTarget'.'

What am I missing to access this.title


Solution

  • this will work

     makeFileRequest(url: string, params: Array<string>) {
    return new Promise((resolve, reject) => {
      var formData: any = new FormData();
      var xhr = new XMLHttpRequest();
      var that = this;
    
      xhr.open("POST", url, true);
      xhr.responseType = 'text';
    
      xhr.onload = function () {
        if (xhr.readyState === xhr.DONE) {
          //trying to get this.title
          console.log(that.title)
        }
      };
      xhr.send(formData);
     });
    }
    }