当我尝试管理XMLHttpRequest调用的结果时,我遇到了一个tslint问题。这是我目前在互联网上找到的方法:
// Files upload request
makeFileRequest(url: string, files: Array<File>) {
return new Promise((resolve, reject) => {
let formData: any = new FormData()
let xhr = new XMLHttpRequest()
for(let file of files) {
formData.append("uploads[]", file, file.name)
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.response))
} else {
reject(xhr.response)
}
}
}
xhr.open("POST", url, true)
xhr.send(formData)
})
}
所以它有效,文件正在上传,后端回复200响应。但在我使用此功能的方法中,我这样做:
this.makeFileRequest("theurl", this.listFiles)
.map(res => res.json())
.subscribe(
res => console.log(res),
error => console.log("fails")
)
但tslint在地图点告诉我这个:
TS2339 Property 'map' does not exist on type 'Promise<{}>'.
所以我认为管理makeFileRequest函数会更好,所以它返回一个Observable而不是Promise。 为了以防万一,请注意我导入“rxjs / add / operator / map”。
有人有什么想法吗?谢谢!
答案 0 :(得分:20)
map
是Observable
的方法,而非Promise
。返回Observable
将修复错误:
makeFileRequest(url: string, files: Array<File>) {
return Observable.fromPromise(new Promise((resolve, reject) => {
let formData: any = new FormData()
let xhr = new XMLHttpRequest()
for (let file of files) {
formData.append("uploads[]", file, file.name)
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.response))
} else {
reject(xhr.response)
}
}
}
xhr.open("POST", url, true)
xhr.send(formData)
}));
}
错误的解决方案:
Property 'json' does not exist on type '{}'
https://stackoverflow.com/a/33919897
不要忘记导入Response
:
import {Response} from '@angular/http';
答案 1 :(得分:0)
实现的简单方法:
xhrCall(url, formData, header) {
return Observable.create(function (observer) {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
observer.next(xhr);
} else {
observer.error(xhr);
}
}
};
xhr.open("POST", url, true);
xhr.setRequestHeader(header.name, header.value);
xhr.send(formData);
});
}