Skip to content

Instantly share code, notes, and snippets.

@ripsware
Last active September 16, 2017 10:04
Show Gist options
  • Save ripsware/e7457f93e62ecd103d87772db9078317 to your computer and use it in GitHub Desktop.
Save ripsware/e7457f93e62ecd103d87772db9078317 to your computer and use it in GitHub Desktop.
import {Injectable} from "@angular/core";
import {Observable} from "rxjs/Observable";
import {Observer} from "rxjs/Observer";
@Injectable()
export class RAjax {
request(
method: string = "GET",
url: string | null,
content: any | null,
additional: any | null = null
): Observable<any> {
var xhttp = new XMLHttpRequest();
if (
!additional ||
(additional &&
!(
additional.headers["Content-Type"] ||
additional.headers["Content-type"] ||
additional.headers["content-type"]
))
) {
xhttp.open(method, url, true);
} else {
xhttp.open(method, url);
}
if (
additional &&
additional.headers &&
additional.headers instanceof Object
) {
for (var key in additional.headers) {
if (
additional.headers[key] &&
typeof additional.headers[key] === "string"
) {
xhttp.setRequestHeader(key, additional.headers[key]);
}
}
}
xhttp.send(
(content &&
content instanceof Object &&
!(content instanceof FormData)
? JSON.stringify(content)
: content) || ""
);
return Observable.create((observer: Observer<any>) => {
xhttp.onload = result => {
var res = xhttp.responseText;
if (
xhttp
.getResponseHeader("Content-type")
.split(";")
.indexOf("application/json") > -1
) {
try {
res = JSON.parse(res);
} catch (error) {
res = xhttp.responseText;
}
}
observer.next({data: res, finished: true, event: result});
};
xhttp.upload.onprogress = e =>
observer.next({
finished: false,
event: {
percentage: Math.floor(e.loaded / e.total * 100),
progress: e.loaded,
total: e.total,
event: e
}
});
xhttp.upload.onerror = er =>
observer.error({error: er, xhr: xhttp});
});
}
get = (url: string, data?: any, additional?: any): Observable<any> => this.request("GET", url, data, additional);
post = (url: string, data?: any, additional?: any): Observable<any> => this.request("POST", url, data, additional);
put = (url: string, data?: any, additional?: any): Observable<any> => this.request("PUT", url, data, additional);
delete = (url: string, data?: any, additional?: any): Observable<any> => this.request("DELETE", url, data, additional);
upload(
url: string,
files: FileList | File[],
param?: any,
additional?: any
): Observable<any> {
const formData = new FormData();
if (files && files.length) {
for (let i = 0; i < files.length; i++) {
formData.set(`file${i + 1}`, files[i], files[i].name);
}
}
if (param) {
for (var k in param) {
formData.set(k, param[k]);
}
}
return this.post(url, formData, additional);
}
}
export interface UploadProgress {
percentage: number;
progress: number;
total: number;
event: ProgressEvent;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment