JavaScript使用angular 2在xhr函数外变量

时间:2017-01-31 06:41:10

标签: javascript angularjs xmlhttprequest

我试图获取在构造函数之前初始化的变量。例如

title: String = 'hello'

从功能中获取(这可行)

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

但是从我原来的代码中,我试图从XHR的onload函数中获取它并且无法访问它。

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' message: 'Property 'title' does not exist on type XMLHttpRequestEventTarget'.'

访问this.title

我缺少什么

1 个答案:

答案 0 :(得分:1)

这将起作用

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