Last active
October 8, 2018 09:08
-
-
Save jagomf/9308fe2201d20651b86cc4cb5ad4b5fc to your computer and use it in GitHub Desktop.
Manually create XHR request for Angular
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
requestName(): Observable<Call> { | |
return new Observable(observer => { | |
const endpoint = 'endpoint'; | |
const data = {}; | |
// #region:multipart | |
// In case of multipart | |
const formData: FormData = new FormData(); | |
Object.keys(data).forEach((key) => { | |
formData.append(key, data[key]); | |
}); | |
// #endregion:multipart | |
const request = new XMLHttpRequest(); | |
request.onreadystatechange = () => { | |
if (request.readyState === 4) { // 4 === XMLHttpRequest.DONE | |
const body = JSON.parse(request.response); | |
if (request.status >= 200 && request.status < 300) { | |
return observer.next(body.data); | |
} else { | |
return observer.error(body.data); | |
} | |
} | |
}; | |
request.open('POST', endpoint); | |
request.setRequestHeader('Authorization', 'Bearer whatever'); | |
request.send(formData); | |
return { unsubscribe() {} }; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment