0
Я пытаюсь получить переменную, которая была инициализирована перед конструктором. НапримерJavaScript, получающий переменную вне функции xhr с использованием угловой 2
title: String = 'hello'
Чтобы получить что из функции (это работает)
functionname() {
//this will work
console.log(this.title)
}
Но из моего оригинального кода, я пытаюсь получить его из функции OnLoad XHR и не смог получить к нему доступ.
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. Cache 'this' класса. Добавьте 'var _this = this;' в обещание выше обратного вызова onload и используйте '_this.title' в обратном вызове. – Tushar
Спасибо, это работает. создайте его как ответ –