1 import { root } from '../../util/root';
2 import { Observable } from '../../Observable';
3 import { Subscriber } from '../../Subscriber';
4 import { map } from '../../operators/map';
5 function getCORSRequest() {
6 if (root.XMLHttpRequest) {
7 return new root.XMLHttpRequest();
9 else if (!!root.XDomainRequest) {
10 return new root.XDomainRequest();
13 throw new Error('CORS is not supported by your browser');
16 function getXMLHttpRequest() {
17 if (root.XMLHttpRequest) {
18 return new root.XMLHttpRequest();
23 const progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'];
24 for (let i = 0; i < 3; i++) {
27 if (new root.ActiveXObject(progId)) {
34 return new root.ActiveXObject(progId);
37 throw new Error('XMLHttpRequest is not supported by your browser');
41 export function ajaxGet(url, headers = null) {
42 return new AjaxObservable({ method: 'GET', url, headers });
44 export function ajaxPost(url, body, headers) {
45 return new AjaxObservable({ method: 'POST', url, body, headers });
47 export function ajaxDelete(url, headers) {
48 return new AjaxObservable({ method: 'DELETE', url, headers });
50 export function ajaxPut(url, body, headers) {
51 return new AjaxObservable({ method: 'PUT', url, body, headers });
53 export function ajaxPatch(url, body, headers) {
54 return new AjaxObservable({ method: 'PATCH', url, body, headers });
56 const mapResponse = map((x, index) => x.response);
57 export function ajaxGetJSON(url, headers) {
58 return mapResponse(new AjaxObservable({
65 export class AjaxObservable extends Observable {
66 constructor(urlOrRequest) {
70 createXHR: function () {
71 return this.crossDomain ? getCORSRequest() : getXMLHttpRequest();
74 withCredentials: false,
80 if (typeof urlOrRequest === 'string') {
81 request.url = urlOrRequest;
84 for (const prop in urlOrRequest) {
85 if (urlOrRequest.hasOwnProperty(prop)) {
86 request[prop] = urlOrRequest[prop];
90 this.request = request;
92 _subscribe(subscriber) {
93 return new AjaxSubscriber(subscriber, this.request);
96 AjaxObservable.create = (() => {
97 const create = (urlOrRequest) => {
98 return new AjaxObservable(urlOrRequest);
100 create.get = ajaxGet;
101 create.post = ajaxPost;
102 create.delete = ajaxDelete;
103 create.put = ajaxPut;
104 create.patch = ajaxPatch;
105 create.getJSON = ajaxGetJSON;
108 export class AjaxSubscriber extends Subscriber {
109 constructor(destination, request) {
111 this.request = request;
113 const headers = request.headers = request.headers || {};
114 if (!request.crossDomain && !this.getHeader(headers, 'X-Requested-With')) {
115 headers['X-Requested-With'] = 'XMLHttpRequest';
117 let contentTypeHeader = this.getHeader(headers, 'Content-Type');
118 if (!contentTypeHeader && !(root.FormData && request.body instanceof root.FormData) && typeof request.body !== 'undefined') {
119 headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
121 request.body = this.serializeBody(request.body, this.getHeader(request.headers, 'Content-Type'));
126 const { xhr, request, destination } = this;
129 result = new AjaxResponse(e, xhr, request);
132 return destination.error(err);
134 destination.next(result);
137 const { request, request: { user, method, url, async, password, headers, body } } = this;
139 const xhr = this.xhr = request.createXHR();
140 this.setupEvents(xhr, request);
142 xhr.open(method, url, async, user, password);
145 xhr.open(method, url, async);
148 xhr.timeout = request.timeout;
149 xhr.responseType = request.responseType;
151 if ('withCredentials' in xhr) {
152 xhr.withCredentials = !!request.withCredentials;
154 this.setHeaders(xhr, headers);
166 serializeBody(body, contentType) {
167 if (!body || typeof body === 'string') {
170 else if (root.FormData && body instanceof root.FormData) {
174 const splitIndex = contentType.indexOf(';');
175 if (splitIndex !== -1) {
176 contentType = contentType.substring(0, splitIndex);
179 switch (contentType) {
180 case 'application/x-www-form-urlencoded':
181 return Object.keys(body).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(body[key])}`).join('&');
182 case 'application/json':
183 return JSON.stringify(body);
188 setHeaders(xhr, headers) {
189 for (let key in headers) {
190 if (headers.hasOwnProperty(key)) {
191 xhr.setRequestHeader(key, headers[key]);
195 getHeader(headers, headerName) {
196 for (let key in headers) {
197 if (key.toLowerCase() === headerName.toLowerCase()) {
203 setupEvents(xhr, request) {
204 const progressSubscriber = request.progressSubscriber;
205 function xhrTimeout(e) {
206 const { subscriber, progressSubscriber, request } = xhrTimeout;
207 if (progressSubscriber) {
208 progressSubscriber.error(e);
212 error = new AjaxTimeoutError(this, request);
217 subscriber.error(error);
219 xhr.ontimeout = xhrTimeout;
220 xhrTimeout.request = request;
221 xhrTimeout.subscriber = this;
222 xhrTimeout.progressSubscriber = progressSubscriber;
223 if (xhr.upload && 'withCredentials' in xhr) {
224 if (progressSubscriber) {
226 xhrProgress = function (e) {
227 const { progressSubscriber } = xhrProgress;
228 progressSubscriber.next(e);
230 if (root.XDomainRequest) {
231 xhr.onprogress = xhrProgress;
234 xhr.upload.onprogress = xhrProgress;
236 xhrProgress.progressSubscriber = progressSubscriber;
239 xhrError = function (e) {
240 const { progressSubscriber, subscriber, request } = xhrError;
241 if (progressSubscriber) {
242 progressSubscriber.error(e);
246 error = new AjaxError('ajax error', this, request);
251 subscriber.error(error);
253 xhr.onerror = xhrError;
254 xhrError.request = request;
255 xhrError.subscriber = this;
256 xhrError.progressSubscriber = progressSubscriber;
258 function xhrReadyStateChange(e) {
261 xhr.onreadystatechange = xhrReadyStateChange;
262 xhrReadyStateChange.subscriber = this;
263 xhrReadyStateChange.progressSubscriber = progressSubscriber;
264 xhrReadyStateChange.request = request;
265 function xhrLoad(e) {
266 const { subscriber, progressSubscriber, request } = xhrLoad;
267 if (this.readyState === 4) {
268 let status = this.status === 1223 ? 204 : this.status;
269 let response = (this.responseType === 'text' ? (this.response || this.responseText) : this.response);
271 status = response ? 200 : 0;
274 if (progressSubscriber) {
275 progressSubscriber.complete();
278 subscriber.complete();
281 if (progressSubscriber) {
282 progressSubscriber.error(e);
286 error = new AjaxError('ajax error ' + status, this, request);
291 subscriber.error(error);
295 xhr.onload = xhrLoad;
296 xhrLoad.subscriber = this;
297 xhrLoad.progressSubscriber = progressSubscriber;
298 xhrLoad.request = request;
301 const { done, xhr } = this;
302 if (!done && xhr && xhr.readyState !== 4 && typeof xhr.abort === 'function') {
308 export class AjaxResponse {
309 constructor(originalEvent, xhr, request) {
310 this.originalEvent = originalEvent;
312 this.request = request;
313 this.status = xhr.status;
314 this.responseType = xhr.responseType || request.responseType;
315 this.response = parseXhrResponse(this.responseType, xhr);
318 const AjaxErrorImpl = (() => {
319 function AjaxErrorImpl(message, xhr, request) {
321 this.message = message;
322 this.name = 'AjaxError';
324 this.request = request;
325 this.status = xhr.status;
326 this.responseType = xhr.responseType || request.responseType;
327 this.response = parseXhrResponse(this.responseType, xhr);
330 AjaxErrorImpl.prototype = Object.create(Error.prototype);
331 return AjaxErrorImpl;
333 export const AjaxError = AjaxErrorImpl;
334 function parseJson(xhr) {
335 if ('response' in xhr) {
336 return xhr.responseType ? xhr.response : JSON.parse(xhr.response || xhr.responseText || 'null');
339 return JSON.parse(xhr.responseText || 'null');
342 function parseXhrResponse(responseType, xhr) {
343 switch (responseType) {
345 return parseJson(xhr);
347 return xhr.responseXML;
350 return ('response' in xhr) ? xhr.response : xhr.responseText;
353 function AjaxTimeoutErrorImpl(xhr, request) {
354 AjaxError.call(this, 'ajax timeout', xhr, request);
355 this.name = 'AjaxTimeoutError';
358 export const AjaxTimeoutError = AjaxTimeoutErrorImpl;
359 //# sourceMappingURL=AjaxObservable.js.map