Skip to content

Instantly share code, notes, and snippets.

@jagomf
Last active October 8, 2018 09:08
Show Gist options
  • Save jagomf/9308fe2201d20651b86cc4cb5ad4b5fc to your computer and use it in GitHub Desktop.
Save jagomf/9308fe2201d20651b86cc4cb5ad4b5fc to your computer and use it in GitHub Desktop.
Manually create XHR request for Angular
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