XMLHttpRequest with Observable in Typescript XMLHttpRequest with Observable in Typescript typescript typescript

XMLHttpRequest with Observable in Typescript


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';


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