typescript 打字稿中带有 Observable 的 XMLHttpRequest

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37749505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:34:00  来源:igfitidea点击:

XMLHttpRequest with Observable in Typescript

typescriptangularxmlhttprequest

提问by Guigui

I have a tslint problem when I try to manage the result of an XMLHttpRequest call I do to upload files. Here is my current method I found on the internet :

当我尝试管理用于上传文件的 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)
    })
}

So it works, the files are being uploaded and the backend replies a 200 response. But in the method where I use this function, I do this :

所以它起作用了,文件正在上传,后端回复 200 响应。但是在我使用这个函数的方法中,我这样做:

        this.makeFileRequest("theurl", this.listFiles)
        .map(res => res.json())
            .subscribe(
                res => console.log(res),
                error => console.log("fails")
            )

But tslint tells me this for at the map point :

但是 tslint 在地图点告诉我这个:

TS2339 Property 'map' does not exist on type 'Promise<{}>'.

So I think it would be better to manage the makeFileRequest function so it returns an Observable instead of a Promise. And just in case, note I import "rxjs/add/operator/map".

所以我认为管理 makeFileRequest 函数会更好,因此它返回一个 Observable 而不是 Promise。以防万一,请注意我导入了“rxjs/add/operator/map”。

Has anyone any idea ? Thanks !

有人知道吗?谢谢 !

回答by Andrei Zhytkevich

mapis a method of Observable, not Promise. Returning an Observablewill fix the error:

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

The solution for the error:

错误的解决方法:

Property 'json' does not exist on type '{}'

https://stackoverflow.com/a/33919897

https://stackoverflow.com/a/33919897

Don't forget to import Response:

不要忘记导入Response

import {Response} from '@angular/http';

回答by Sahil Ralkar

The simple way to achieve:

实现的简单方法:

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