XMLHttpRequest with Observable in Typescript

前端 未结 2 622
小蘑菇
小蘑菇 2021-02-19 08:54

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 :

// Fi         


        
2条回答
  •  难免孤独
    2021-02-19 09:34

    map is a method of Observable, not Promise. Returning an Observable will fix the error:

    makeFileRequest(url: string, files: Array) {
        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

    Don't forget to import Response:

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

提交回复
热议问题