【问题标题】:JavaScript getting variable outside xhr function using angular 2 [duplicate]JavaScript使用角度2在xhr函数之外获取变量[重复]
【发布时间】:2017-01-31 14:48:03
【问题描述】:

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

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 缺少什么

【问题讨论】:

  • this 指的是 XHR。缓存类的this。在onload回调上面的promise中添加var _this = this;,并在回调中使用_this.title
  • 谢谢,这行得通。请创建它作为答案

标签: javascript angularjs xmlhttprequest


【解决方案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);
 });
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    • 1970-01-01
    相关资源
    最近更新 更多