Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest with Observable in Typescript

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 :

// 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 :

        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 :

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".

Has anyone any idea ? Thanks !

like image 568
Guigui Avatar asked Jun 10 '16 13:06

Guigui


People also ask

Can I use XMLHttpRequest in Angular?

XHR stands for XMLHttpRequest, and it's an API we can use to make AJAX requests in JavaScript. Using this API, we can make a network request to exchange data from website to server. XHR is used to make HTTP requests in JavaScript, but it's not the most modern approach.

Is Angular Http Observable?

Angular makes use of observables as an interface to handle a variety of common asynchronous operations. For example: The HTTP module uses observables to handle AJAX requests and responses.


1 Answers

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

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

Don't forget to import Response:

import {Response} from '@angular/http';
like image 135
Andrei Zhytkevich Avatar answered Oct 09 '22 13:10

Andrei Zhytkevich