-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.ts
73 lines (65 loc) · 2.37 KB
/
http.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { Subject, Observable } from 'rxjs/Rx';
export class Http {
public response: any;
private resp: Subject<any> = new Subject<any>();
public error: any;
public status: any;
public success: boolean;
public response$ = this.resp.asObservable();
constructor() {
}
public make = async (opts: any): Promise<any> => {
let that = this;
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
that.response = null;
that.error = null;
that.status = "executing";
xhr.open(opts.method, opts.url, true);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
that.response = xhr.response;
that.resp.next(that.response);
that.status = "complete";
that.success = true;
resolve(xhr.response);
} else {
that.error = {
status: this.status,
statusText: xhr.statusText
};
that.status = "complete";
that.resp.next(that.error);
that.success = false;
reject(that.error);
}
};
xhr.onerror = function () {
that.error = {
status: this.status,
statusText: xhr.statusText
};
that.status = "complete";
that.resp.next(that.error);
that.success = false;
reject(that.error);
};
if (opts.headers) {
Object.keys(opts.headers).forEach(function (key) {
xhr.setRequestHeader(key, opts.headers[key]);
});
}
var params = opts.data;
var process = opts.process;
if (process == undefined) process = true;
if (process == true) {
if (params && typeof params === 'object') {
params = Object.keys(params).map(function (key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
}
}
xhr.send(params);
});
};
}