UNPKG

@reactivex/rxjs

Version:

Reactive Extensions for modern JavaScript

472 lines (462 loc) 22.4 kB
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <base data-ice="baseUrl" href="../../../../"> <title data-ice="title">es6/observable/dom/AjaxObservable.js | RxJS API Document</title> <link type="text/css" rel="stylesheet" href="css/style.css"> <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css"> <script src="script/prettify/prettify.js"></script> <script src="script/manual.js"></script> <script data-ice="userScript" src="user/script/0-Rx.js"></script> <script data-ice="userScript" src="user/script/1-devtools-welcome.js"></script> <script data-ice="userScript" src="user/script/2-custom-manual-styles.js"></script> <script data-ice="userScript" src="user/script/3-decision-tree-widget.min.js"></script> <script data-ice="userScript" src="user/script/4-theme-toggler.js"></script> <link data-ice="userStyle" rel="stylesheet" href="user/css/0-main.css"> </head> <body class="layout-container" data-ice="rootContainer"> <header> <a href="./">Home</a> <a href="./manual/index.html" data-ice="manualHeaderLink">Manual</a> <a href="identifiers.html">Reference</a> <a href="source.html">Source</a> <a href="test.html" data-ice="testLink">Test</a> <a data-ice="repoURL" href="https://github.com/ReactiveX/RxJS" class="repo-url-github">Repository</a> <div class="search-box"> <span> <img src="./image/search.png"> <span class="search-input-edge"></span><input class="search-input"><span class="search-input-edge"></span> </span> <ul class="search-result"></ul> </div> </header> <nav class="navigation" data-ice="nav"><div> <ul> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-AsyncSubject">AsyncSubject</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-BehaviorSubject">BehaviorSubject</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-Notification">Notification</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-Observable">Observable</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-ReplaySubject">ReplaySubject</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-Scheduler">Scheduler</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-AnonymousSubject">AnonymousSubject</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-Subject">Subject</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-SubjectSubscriber">SubjectSubscriber</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-Subscriber">Subscriber</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-Subscription">Subscription</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-typedef">T</span><span data-ice="name"><span><a href="typedef/index.html#static-typedef-Rx.Scheduler">Rx.Scheduler</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-typedef">T</span><span data-ice="name"><span><a href="typedef/index.html#static-typedef-Rx.Symbol">Rx.Symbol</a></span></span></li> <li data-ice="doc"><div data-ice="dirPath" class="nav-dir-path">observable</div><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-ConnectableObservable">ConnectableObservable</a></span></span></li> <li data-ice="doc"><div data-ice="dirPath" class="nav-dir-path">observable/dom</div><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-AjaxError">AjaxError</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-AjaxResponse">AjaxResponse</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-AjaxTimeoutError">AjaxTimeoutError</a></span></span></li> <li data-ice="doc"><div data-ice="dirPath" class="nav-dir-path">operator</div><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-GroupedObservable">GroupedObservable</a></span></span></li> <li data-ice="doc"><div data-ice="dirPath" class="nav-dir-path">scheduler</div><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-Action">Action</a></span></span></li> <li data-ice="doc"><div data-ice="dirPath" class="nav-dir-path">util</div><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-ArgumentOutOfRangeError">ArgumentOutOfRangeError</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-EmptyError">EmptyError</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-ObjectUnsubscribedError">ObjectUnsubscribedError</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-TimeoutError">TimeoutError</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-UnsubscriptionError">UnsubscriptionError</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-root">root</a></span></span></li> </ul> </div> </nav> <div class="content" data-ice="content"><h1 data-ice="title">es6/observable/dom/AjaxObservable.js</h1> <pre class="source-code line-number raw-source-code"><code class="prettyprint linenums" data-ice="content">import { root } from &apos;../../util/root&apos;; import { tryCatch } from &apos;../../util/tryCatch&apos;; import { errorObject } from &apos;../../util/errorObject&apos;; import { Observable } from &apos;../../Observable&apos;; import { Subscriber } from &apos;../../Subscriber&apos;; import { MapOperator } from &apos;../../operator/map&apos;; function getCORSRequest() { if (root.XMLHttpRequest) { var xhr = new root.XMLHttpRequest(); if (&apos;withCredentials&apos; in xhr) { xhr.withCredentials = !!this.withCredentials; } return xhr; } else if (!!root.XDomainRequest) { return new root.XDomainRequest(); } else { throw new Error(&apos;CORS is not supported by your browser&apos;); } } function getXMLHttpRequest() { if (root.XMLHttpRequest) { return new root.XMLHttpRequest(); } else { var progId = void 0; try { var progIds = [&apos;Msxml2.XMLHTTP&apos;, &apos;Microsoft.XMLHTTP&apos;, &apos;Msxml2.XMLHTTP.4.0&apos;]; for (var i = 0; i &lt; 3; i++) { try { progId = progIds[i]; if (new root.ActiveXObject(progId)) { break; } } catch (e) { } } return new root.ActiveXObject(progId); } catch (e) { throw new Error(&apos;XMLHttpRequest is not supported by your browser&apos;); } } } export function ajaxGet(url, headers) { if (headers === void 0) { headers = null; } return new AjaxObservable({ method: &apos;GET&apos;, url: url, headers: headers }); } ; export function ajaxPost(url, body, headers) { return new AjaxObservable({ method: &apos;POST&apos;, url: url, body: body, headers: headers }); } ; export function ajaxDelete(url, headers) { return new AjaxObservable({ method: &apos;DELETE&apos;, url: url, headers: headers }); } ; export function ajaxPut(url, body, headers) { return new AjaxObservable({ method: &apos;PUT&apos;, url: url, body: body, headers: headers }); } ; export function ajaxGetJSON(url, headers) { return new AjaxObservable({ method: &apos;GET&apos;, url: url, responseType: &apos;json&apos;, headers: headers }) .lift(new MapOperator(function (x, index) { return x.response; }, null)); } ; /** * We need this JSDoc comment for affecting ESDoc. * @extends {Ignored} * @hide true */ export var AjaxObservable = (function (_super) { __extends(AjaxObservable, _super); function AjaxObservable(urlOrRequest) { _super.call(this); var request = { async: true, createXHR: function () { return this.crossDomain ? getCORSRequest.call(this) : getXMLHttpRequest(); }, crossDomain: false, withCredentials: false, headers: {}, method: &apos;GET&apos;, responseType: &apos;json&apos;, timeout: 0 }; if (typeof urlOrRequest === &apos;string&apos;) { request.url = urlOrRequest; } else { for (var prop in urlOrRequest) { if (urlOrRequest.hasOwnProperty(prop)) { request[prop] = urlOrRequest[prop]; } } } this.request = request; } AjaxObservable.prototype._subscribe = function (subscriber) { return new AjaxSubscriber(subscriber, this.request); }; /** * Creates an observable for an Ajax request with either a request object with * url, headers, etc or a string for a URL. * * @example * source = Rx.Observable.ajax(&apos;/products&apos;); * source = Rx.Observable.ajax({ url: &apos;products&apos;, method: &apos;GET&apos; }); * * @param {string|Object} request Can be one of the following: * A string of the URL to make the Ajax call. * An object with the following properties * - url: URL of the request * - body: The body of the request * - method: Method of the request, such as GET, POST, PUT, PATCH, DELETE * - async: Whether the request is async * - headers: Optional headers * - crossDomain: true if a cross domain request, else false * - createXHR: a function to override if you need to use an alternate * XMLHttpRequest implementation. * - resultSelector: a function to use to alter the output value type of * the Observable. Gets {@link AjaxResponse} as an argument. * @return {Observable} An observable sequence containing the XMLHttpRequest. * @static true * @name ajax * @owner Observable */ AjaxObservable.create = (function () { var create = function (urlOrRequest) { return new AjaxObservable(urlOrRequest); }; create.get = ajaxGet; create.post = ajaxPost; create.delete = ajaxDelete; create.put = ajaxPut; create.getJSON = ajaxGetJSON; return create; })(); return AjaxObservable; }(Observable)); /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ export var AjaxSubscriber = (function (_super) { __extends(AjaxSubscriber, _super); function AjaxSubscriber(destination, request) { _super.call(this, destination); this.request = request; this.done = false; var headers = request.headers = request.headers || {}; // force CORS if requested if (!request.crossDomain &amp;&amp; !headers[&apos;X-Requested-With&apos;]) { headers[&apos;X-Requested-With&apos;] = &apos;XMLHttpRequest&apos;; } // ensure content type is set if (!(&apos;Content-Type&apos; in headers) &amp;&amp; !(root.FormData &amp;&amp; request.body instanceof root.FormData) &amp;&amp; typeof request.body !== &apos;undefined&apos;) { headers[&apos;Content-Type&apos;] = &apos;application/x-www-form-urlencoded; charset=UTF-8&apos;; } // properly serialize body request.body = this.serializeBody(request.body, request.headers[&apos;Content-Type&apos;]); this.send(); } AjaxSubscriber.prototype.next = function (e) { this.done = true; var _a = this, xhr = _a.xhr, request = _a.request, destination = _a.destination; var response = new AjaxResponse(e, xhr, request); destination.next(response); }; AjaxSubscriber.prototype.send = function () { var _a = this, request = _a.request, _b = _a.request, user = _b.user, method = _b.method, url = _b.url, async = _b.async, password = _b.password, headers = _b.headers, body = _b.body; var createXHR = request.createXHR; var xhr = tryCatch(createXHR).call(request); if (xhr === errorObject) { this.error(errorObject.e); } else { this.xhr = xhr; // open XHR first var result = void 0; if (user) { result = tryCatch(xhr.open).call(xhr, method, url, async, user, password); } else { result = tryCatch(xhr.open).call(xhr, method, url, async); } if (result === errorObject) { this.error(errorObject.e); return null; } // timeout and responseType can be set once the XHR is open xhr.timeout = request.timeout; xhr.responseType = request.responseType; // set headers this.setHeaders(xhr, headers); // now set up the events this.setupEvents(xhr, request); // finally send the request if (body) { xhr.send(body); } else { xhr.send(); } } return xhr; }; AjaxSubscriber.prototype.serializeBody = function (body, contentType) { if (!body || typeof body === &apos;string&apos;) { return body; } else if (root.FormData &amp;&amp; body instanceof root.FormData) { return body; } if (contentType) { var splitIndex = contentType.indexOf(&apos;;&apos;); if (splitIndex !== -1) { contentType = contentType.substring(0, splitIndex); } } switch (contentType) { case &apos;application/x-www-form-urlencoded&apos;: return Object.keys(body).map(function (key) { return (encodeURI(key) + &quot;=&quot; + encodeURI(body[key])); }).join(&apos;&amp;&apos;); case &apos;application/json&apos;: return JSON.stringify(body); default: return body; } }; AjaxSubscriber.prototype.setHeaders = function (xhr, headers) { for (var key in headers) { if (headers.hasOwnProperty(key)) { xhr.setRequestHeader(key, headers[key]); } } }; AjaxSubscriber.prototype.setupEvents = function (xhr, request) { var progressSubscriber = request.progressSubscriber; function xhrTimeout(e) { var _a = xhrTimeout, subscriber = _a.subscriber, progressSubscriber = _a.progressSubscriber, request = _a.request; if (progressSubscriber) { progressSubscriber.error(e); } subscriber.error(new AjaxTimeoutError(this, request)); //TODO: Make betterer. } ; xhr.ontimeout = xhrTimeout; xhrTimeout.request = request; xhrTimeout.subscriber = this; xhrTimeout.progressSubscriber = progressSubscriber; if (xhr.upload &amp;&amp; &apos;withCredentials&apos; in xhr &amp;&amp; root.XDomainRequest) { if (progressSubscriber) { var xhrProgress_1; xhrProgress_1 = function (e) { var progressSubscriber = xhrProgress_1.progressSubscriber; progressSubscriber.next(e); }; xhr.onprogress = xhrProgress_1; xhrProgress_1.progressSubscriber = progressSubscriber; } var xhrError_1; xhrError_1 = function (e) { var _a = xhrError_1, progressSubscriber = _a.progressSubscriber, subscriber = _a.subscriber, request = _a.request; if (progressSubscriber) { progressSubscriber.error(e); } subscriber.error(new AjaxError(&apos;ajax error&apos;, this, request)); }; xhr.onerror = xhrError_1; xhrError_1.request = request; xhrError_1.subscriber = this; xhrError_1.progressSubscriber = progressSubscriber; } function xhrReadyStateChange(e) { var _a = xhrReadyStateChange, subscriber = _a.subscriber, progressSubscriber = _a.progressSubscriber, request = _a.request; if (this.readyState === 4) { // normalize IE9 bug (http://bugs.jquery.com/ticket/1450) var status_1 = this.status === 1223 ? 204 : this.status; var response = (this.responseType === &apos;text&apos; ? (this.response || this.responseText) : this.response); // fix status code when it is 0 (0 status is undocumented). // Occurs when accessing file resources or on Android 4.1 stock browser // while retrieving files from application cache. if (status_1 === 0) { status_1 = response ? 200 : 0; } if (200 &lt;= status_1 &amp;&amp; status_1 &lt; 300) { if (progressSubscriber) { progressSubscriber.complete(); } subscriber.next(e); subscriber.complete(); } else { if (progressSubscriber) { progressSubscriber.error(e); } subscriber.error(new AjaxError(&apos;ajax error &apos; + status_1, this, request)); } } } ; xhr.onreadystatechange = xhrReadyStateChange; xhrReadyStateChange.subscriber = this; xhrReadyStateChange.progressSubscriber = progressSubscriber; xhrReadyStateChange.request = request; }; AjaxSubscriber.prototype.unsubscribe = function () { var _a = this, done = _a.done, xhr = _a.xhr; if (!done &amp;&amp; xhr &amp;&amp; xhr.readyState !== 4 &amp;&amp; typeof xhr.abort === &apos;function&apos;) { xhr.abort(); } _super.prototype.unsubscribe.call(this); }; return AjaxSubscriber; }(Subscriber)); /** * A normalized AJAX response. * * @see {@link ajax} * * @class AjaxResponse */ export var AjaxResponse = (function () { function AjaxResponse(originalEvent, xhr, request) { this.originalEvent = originalEvent; this.xhr = xhr; this.request = request; this.status = xhr.status; this.responseType = xhr.responseType || request.responseType; switch (this.responseType) { case &apos;json&apos;: if (&apos;response&apos; in xhr) { //IE does not support json as responseType, parse it internally this.response = xhr.responseType ? xhr.response : JSON.parse(xhr.response || xhr.responseText || &apos;null&apos;); } else { this.response = JSON.parse(xhr.responseText || &apos;null&apos;); } break; case &apos;xml&apos;: this.response = xhr.responseXML; break; case &apos;text&apos;: default: this.response = (&apos;response&apos; in xhr) ? xhr.response : xhr.responseText; break; } } return AjaxResponse; }()); /** * A normalized AJAX error. * * @see {@link ajax} * * @class AjaxError */ export var AjaxError = (function (_super) { __extends(AjaxError, _super); function AjaxError(message, xhr, request) { _super.call(this, message); this.message = message; this.xhr = xhr; this.request = request; this.status = xhr.status; } return AjaxError; }(Error)); /** * @see {@link ajax} * * @class AjaxTimeoutError */ export var AjaxTimeoutError = (function (_super) { __extends(AjaxTimeoutError, _super); function AjaxTimeoutError(xhr, request) { _super.call(this, &apos;ajax timeout&apos;, xhr, request); } return AjaxTimeoutError; }(AjaxError)); //# sourceMappingURL=AjaxObservable.js.map</code></pre> </div> <footer class="footer"> Generated by <a href="https://esdoc.org">ESDoc<span data-ice="esdocVersion">(0.4.8)</span></a> </footer> <script src="script/search_index.js"></script> <script src="script/search.js"></script> <script src="script/pretty-print.js"></script> <script src="script/inherited-summary.js"></script> <script src="script/test-summary.js"></script> <script src="script/inner-link.js"></script> <script src="script/patch-for-local.js"></script> </body> </html>