JavaScript 使用 Angular 2 在 xhr 函数外部获取变量

标签 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 时我缺少什么

最佳答案

这会起作用

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

关于JavaScript 使用 Angular 2 在 xhr 函数外部获取变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41951196/

相关文章:

javascript - ionic : How is it possible to change $ionicPopup subTitle's text programmatically?

javascript - Microsoft Edge 阻止跨域请求

amazon-web-services - 从 AWS Amplify 部署的 HTTPS (SSL) 客户端向 HTTP 端点发出 API 请求

javascript - MVC - 用户双击“提交”按钮的问题

javascript - 相当于JQuery中Angular Js的编译链接功能

c# - 将 google recaptcha 与 Angular 和 WebAPI 结合使用

javascript - 单击事件处理程序中的 XMLHttpRequest 状态 0

javascript - mongodb 查找与 $elemMatch 相反的

javascript - 在运行时创建具有动态内容和调用函数的 JavaScript 文件

javascript - Fabric.js Canvas 图像抗锯齿