common-http.umd.js 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125
  1. /**
  2. * @license Angular v8.1.0
  3. * (c) 2010-2019 Google LLC. https://angular.io/
  4. * License: MIT
  5. */
  6. (function (global, factory) {
  7. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('rxjs'), require('rxjs/operators'), require('@angular/common')) :
  8. typeof define === 'function' && define.amd ? define('@angular/common/http', ['exports', '@angular/core', 'rxjs', 'rxjs/operators', '@angular/common'], factory) :
  9. (global = global || self, factory((global.ng = global.ng || {}, global.ng.common = global.ng.common || {}, global.ng.common.http = {}), global.ng.core, global.rxjs, global.rxjs.operators, global.ng.common));
  10. }(this, function (exports, core, rxjs, operators, common) { 'use strict';
  11. /**
  12. * @license
  13. * Copyright Google Inc. All Rights Reserved.
  14. *
  15. * Use of this source code is governed by an MIT-style license that can be
  16. * found in the LICENSE file at https://angular.io/license
  17. */
  18. /**
  19. * Transforms an `HttpRequest` into a stream of `HttpEvent`s, one of which will likely be a
  20. * `HttpResponse`.
  21. *
  22. * `HttpHandler` is injectable. When injected, the handler instance dispatches requests to the
  23. * first interceptor in the chain, which dispatches to the second, etc, eventually reaching the
  24. * `HttpBackend`.
  25. *
  26. * In an `HttpInterceptor`, the `HttpHandler` parameter is the next interceptor in the chain.
  27. *
  28. * @publicApi
  29. */
  30. var HttpHandler = /** @class */ (function () {
  31. function HttpHandler() {
  32. }
  33. return HttpHandler;
  34. }());
  35. /**
  36. * A final `HttpHandler` which will dispatch the request via browser HTTP APIs to a backend.
  37. *
  38. * Interceptors sit between the `HttpClient` interface and the `HttpBackend`.
  39. *
  40. * When injected, `HttpBackend` dispatches requests directly to the backend, without going
  41. * through the interceptor chain.
  42. *
  43. * @publicApi
  44. */
  45. var HttpBackend = /** @class */ (function () {
  46. function HttpBackend() {
  47. }
  48. return HttpBackend;
  49. }());
  50. /*! *****************************************************************************
  51. Copyright (c) Microsoft Corporation. All rights reserved.
  52. Licensed under the Apache License, Version 2.0 (the "License"); you may not use
  53. this file except in compliance with the License. You may obtain a copy of the
  54. License at http://www.apache.org/licenses/LICENSE-2.0
  55. THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56. KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
  57. WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
  58. MERCHANTABLITY OR NON-INFRINGEMENT.
  59. See the Apache Version 2.0 License for specific language governing permissions
  60. and limitations under the License.
  61. ***************************************************************************** */
  62. /* global Reflect, Promise */
  63. var extendStatics = function(d, b) {
  64. extendStatics = Object.setPrototypeOf ||
  65. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  66. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  67. return extendStatics(d, b);
  68. };
  69. function __extends(d, b) {
  70. extendStatics(d, b);
  71. function __() { this.constructor = d; }
  72. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  73. }
  74. function __decorate(decorators, target, key, desc) {
  75. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  76. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  77. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  78. return c > 3 && r && Object.defineProperty(target, key, r), r;
  79. }
  80. function __param(paramIndex, decorator) {
  81. return function (target, key) { decorator(target, key, paramIndex); }
  82. }
  83. function __metadata(metadataKey, metadataValue) {
  84. if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
  85. }
  86. function __read(o, n) {
  87. var m = typeof Symbol === "function" && o[Symbol.iterator];
  88. if (!m) return o;
  89. var i = m.call(o), r, ar = [], e;
  90. try {
  91. while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  92. }
  93. catch (error) { e = { error: error }; }
  94. finally {
  95. try {
  96. if (r && !r.done && (m = i["return"])) m.call(i);
  97. }
  98. finally { if (e) throw e.error; }
  99. }
  100. return ar;
  101. }
  102. function __spread() {
  103. for (var ar = [], i = 0; i < arguments.length; i++)
  104. ar = ar.concat(__read(arguments[i]));
  105. return ar;
  106. }
  107. /**
  108. * @license
  109. * Copyright Google Inc. All Rights Reserved.
  110. *
  111. * Use of this source code is governed by an MIT-style license that can be
  112. * found in the LICENSE file at https://angular.io/license
  113. */
  114. /**
  115. * `HttpHeaders` class represents the header configuration options for an HTTP request.
  116. * Instances should be assumed immutable with lazy parsing.
  117. *
  118. * @publicApi
  119. */
  120. var HttpHeaders = /** @class */ (function () {
  121. /** Constructs a new HTTP header object with the given values.*/
  122. function HttpHeaders(headers) {
  123. var _this = this;
  124. /**
  125. * Internal map of lowercased header names to the normalized
  126. * form of the name (the form seen first).
  127. */
  128. this.normalizedNames = new Map();
  129. /**
  130. * Queued updates to be materialized the next initialization.
  131. */
  132. this.lazyUpdate = null;
  133. if (!headers) {
  134. this.headers = new Map();
  135. }
  136. else if (typeof headers === 'string') {
  137. this.lazyInit = function () {
  138. _this.headers = new Map();
  139. headers.split('\n').forEach(function (line) {
  140. var index = line.indexOf(':');
  141. if (index > 0) {
  142. var name_1 = line.slice(0, index);
  143. var key = name_1.toLowerCase();
  144. var value = line.slice(index + 1).trim();
  145. _this.maybeSetNormalizedName(name_1, key);
  146. if (_this.headers.has(key)) {
  147. _this.headers.get(key).push(value);
  148. }
  149. else {
  150. _this.headers.set(key, [value]);
  151. }
  152. }
  153. });
  154. };
  155. }
  156. else {
  157. this.lazyInit = function () {
  158. _this.headers = new Map();
  159. Object.keys(headers).forEach(function (name) {
  160. var values = headers[name];
  161. var key = name.toLowerCase();
  162. if (typeof values === 'string') {
  163. values = [values];
  164. }
  165. if (values.length > 0) {
  166. _this.headers.set(key, values);
  167. _this.maybeSetNormalizedName(name, key);
  168. }
  169. });
  170. };
  171. }
  172. }
  173. /**
  174. * Checks for existence of a header by a given name.
  175. *
  176. * @param name The header name to check for existence.
  177. *
  178. * @returns Whether the header exits.
  179. */
  180. HttpHeaders.prototype.has = function (name) {
  181. this.init();
  182. return this.headers.has(name.toLowerCase());
  183. };
  184. /**
  185. * Returns the first header value that matches a given name.
  186. *
  187. * @param name The header name to retrieve.
  188. *
  189. * @returns A string if the header exists, null otherwise
  190. */
  191. HttpHeaders.prototype.get = function (name) {
  192. this.init();
  193. var values = this.headers.get(name.toLowerCase());
  194. return values && values.length > 0 ? values[0] : null;
  195. };
  196. /**
  197. * Returns the names of the headers.
  198. *
  199. * @returns A list of header names.
  200. */
  201. HttpHeaders.prototype.keys = function () {
  202. this.init();
  203. return Array.from(this.normalizedNames.values());
  204. };
  205. /**
  206. * Returns a list of header values for a given header name.
  207. *
  208. * @param name The header name from which to retrieve the values.
  209. *
  210. * @returns A string of values if the header exists, null otherwise.
  211. */
  212. HttpHeaders.prototype.getAll = function (name) {
  213. this.init();
  214. return this.headers.get(name.toLowerCase()) || null;
  215. };
  216. /**
  217. * Appends a new header value to the existing set of
  218. * header values.
  219. *
  220. * @param name The header name for which to append the values.
  221. *
  222. * @returns A clone of the HTTP header object with the value appended.
  223. */
  224. HttpHeaders.prototype.append = function (name, value) {
  225. return this.clone({ name: name, value: value, op: 'a' });
  226. };
  227. /**
  228. * Sets a header value for a given name. If the header name already exists,
  229. * its value is replaced with the given value.
  230. *
  231. * @param name The header name.
  232. * @param value Provides the value to set or overide for a given name.
  233. *
  234. * @returns A clone of the HTTP header object with the newly set header value.
  235. */
  236. HttpHeaders.prototype.set = function (name, value) {
  237. return this.clone({ name: name, value: value, op: 's' });
  238. };
  239. /**
  240. * Deletes all header values for a given name.
  241. *
  242. * @param name The header name.
  243. * @param value The header values to delete for a given name.
  244. *
  245. * @returns A clone of the HTTP header object.
  246. */
  247. HttpHeaders.prototype.delete = function (name, value) {
  248. return this.clone({ name: name, value: value, op: 'd' });
  249. };
  250. HttpHeaders.prototype.maybeSetNormalizedName = function (name, lcName) {
  251. if (!this.normalizedNames.has(lcName)) {
  252. this.normalizedNames.set(lcName, name);
  253. }
  254. };
  255. HttpHeaders.prototype.init = function () {
  256. var _this = this;
  257. if (!!this.lazyInit) {
  258. if (this.lazyInit instanceof HttpHeaders) {
  259. this.copyFrom(this.lazyInit);
  260. }
  261. else {
  262. this.lazyInit();
  263. }
  264. this.lazyInit = null;
  265. if (!!this.lazyUpdate) {
  266. this.lazyUpdate.forEach(function (update) { return _this.applyUpdate(update); });
  267. this.lazyUpdate = null;
  268. }
  269. }
  270. };
  271. HttpHeaders.prototype.copyFrom = function (other) {
  272. var _this = this;
  273. other.init();
  274. Array.from(other.headers.keys()).forEach(function (key) {
  275. _this.headers.set(key, other.headers.get(key));
  276. _this.normalizedNames.set(key, other.normalizedNames.get(key));
  277. });
  278. };
  279. HttpHeaders.prototype.clone = function (update) {
  280. var clone = new HttpHeaders();
  281. clone.lazyInit =
  282. (!!this.lazyInit && this.lazyInit instanceof HttpHeaders) ? this.lazyInit : this;
  283. clone.lazyUpdate = (this.lazyUpdate || []).concat([update]);
  284. return clone;
  285. };
  286. HttpHeaders.prototype.applyUpdate = function (update) {
  287. var key = update.name.toLowerCase();
  288. switch (update.op) {
  289. case 'a':
  290. case 's':
  291. var value = update.value;
  292. if (typeof value === 'string') {
  293. value = [value];
  294. }
  295. if (value.length === 0) {
  296. return;
  297. }
  298. this.maybeSetNormalizedName(update.name, key);
  299. var base = (update.op === 'a' ? this.headers.get(key) : undefined) || [];
  300. base.push.apply(base, __spread(value));
  301. this.headers.set(key, base);
  302. break;
  303. case 'd':
  304. var toDelete_1 = update.value;
  305. if (!toDelete_1) {
  306. this.headers.delete(key);
  307. this.normalizedNames.delete(key);
  308. }
  309. else {
  310. var existing = this.headers.get(key);
  311. if (!existing) {
  312. return;
  313. }
  314. existing = existing.filter(function (value) { return toDelete_1.indexOf(value) === -1; });
  315. if (existing.length === 0) {
  316. this.headers.delete(key);
  317. this.normalizedNames.delete(key);
  318. }
  319. else {
  320. this.headers.set(key, existing);
  321. }
  322. }
  323. break;
  324. }
  325. };
  326. /**
  327. * @internal
  328. */
  329. HttpHeaders.prototype.forEach = function (fn) {
  330. var _this = this;
  331. this.init();
  332. Array.from(this.normalizedNames.keys())
  333. .forEach(function (key) { return fn(_this.normalizedNames.get(key), _this.headers.get(key)); });
  334. };
  335. return HttpHeaders;
  336. }());
  337. /**
  338. * @license
  339. * Copyright Google Inc. All Rights Reserved.
  340. *
  341. * Use of this source code is governed by an MIT-style license that can be
  342. * found in the LICENSE file at https://angular.io/license
  343. */
  344. /**
  345. * A class that uses `encodeURIComponent` and `decodeURIComponent` to
  346. * serialize and parse URL parameter keys and values. If you pass URL query parameters
  347. * without encoding, the query parameters can get misinterpreted at the receiving end.
  348. * Use the `HttpParameterCodec` class to encode and decode the query-string values.
  349. *
  350. * @publicApi
  351. */
  352. var HttpUrlEncodingCodec = /** @class */ (function () {
  353. function HttpUrlEncodingCodec() {
  354. }
  355. HttpUrlEncodingCodec.prototype.encodeKey = function (key) { return standardEncoding(key); };
  356. HttpUrlEncodingCodec.prototype.encodeValue = function (value) { return standardEncoding(value); };
  357. HttpUrlEncodingCodec.prototype.decodeKey = function (key) { return decodeURIComponent(key); };
  358. HttpUrlEncodingCodec.prototype.decodeValue = function (value) { return decodeURIComponent(value); };
  359. return HttpUrlEncodingCodec;
  360. }());
  361. function paramParser(rawParams, codec) {
  362. var map = new Map();
  363. if (rawParams.length > 0) {
  364. var params = rawParams.split('&');
  365. params.forEach(function (param) {
  366. var eqIdx = param.indexOf('=');
  367. var _a = __read(eqIdx == -1 ?
  368. [codec.decodeKey(param), ''] :
  369. [codec.decodeKey(param.slice(0, eqIdx)), codec.decodeValue(param.slice(eqIdx + 1))], 2), key = _a[0], val = _a[1];
  370. var list = map.get(key) || [];
  371. list.push(val);
  372. map.set(key, list);
  373. });
  374. }
  375. return map;
  376. }
  377. function standardEncoding(v) {
  378. return encodeURIComponent(v)
  379. .replace(/%40/gi, '@')
  380. .replace(/%3A/gi, ':')
  381. .replace(/%24/gi, '$')
  382. .replace(/%2C/gi, ',')
  383. .replace(/%3B/gi, ';')
  384. .replace(/%2B/gi, '+')
  385. .replace(/%3D/gi, '=')
  386. .replace(/%3F/gi, '?')
  387. .replace(/%2F/gi, '/');
  388. }
  389. /**
  390. * An HTTP request/response body that represents serialized parameters,
  391. * per the MIME type `application/x-www-form-urlencoded`.
  392. *
  393. * This class is immutable - all mutation operations return a new instance.
  394. *
  395. * @publicApi
  396. */
  397. var HttpParams = /** @class */ (function () {
  398. function HttpParams(options) {
  399. var _this = this;
  400. if (options === void 0) { options = {}; }
  401. this.updates = null;
  402. this.cloneFrom = null;
  403. this.encoder = options.encoder || new HttpUrlEncodingCodec();
  404. if (!!options.fromString) {
  405. if (!!options.fromObject) {
  406. throw new Error("Cannot specify both fromString and fromObject.");
  407. }
  408. this.map = paramParser(options.fromString, this.encoder);
  409. }
  410. else if (!!options.fromObject) {
  411. this.map = new Map();
  412. Object.keys(options.fromObject).forEach(function (key) {
  413. var value = options.fromObject[key];
  414. _this.map.set(key, Array.isArray(value) ? value : [value]);
  415. });
  416. }
  417. else {
  418. this.map = null;
  419. }
  420. }
  421. /**
  422. * Check whether the body has one or more values for the given parameter name.
  423. */
  424. HttpParams.prototype.has = function (param) {
  425. this.init();
  426. return this.map.has(param);
  427. };
  428. /**
  429. * Get the first value for the given parameter name, or `null` if it's not present.
  430. */
  431. HttpParams.prototype.get = function (param) {
  432. this.init();
  433. var res = this.map.get(param);
  434. return !!res ? res[0] : null;
  435. };
  436. /**
  437. * Get all values for the given parameter name, or `null` if it's not present.
  438. */
  439. HttpParams.prototype.getAll = function (param) {
  440. this.init();
  441. return this.map.get(param) || null;
  442. };
  443. /**
  444. * Get all the parameter names for this body.
  445. */
  446. HttpParams.prototype.keys = function () {
  447. this.init();
  448. return Array.from(this.map.keys());
  449. };
  450. /**
  451. * Construct a new body with an appended value for the given parameter name.
  452. */
  453. HttpParams.prototype.append = function (param, value) { return this.clone({ param: param, value: value, op: 'a' }); };
  454. /**
  455. * Construct a new body with a new value for the given parameter name.
  456. */
  457. HttpParams.prototype.set = function (param, value) { return this.clone({ param: param, value: value, op: 's' }); };
  458. /**
  459. * Construct a new body with either the given value for the given parameter
  460. * removed, if a value is given, or all values for the given parameter removed
  461. * if not.
  462. */
  463. HttpParams.prototype.delete = function (param, value) { return this.clone({ param: param, value: value, op: 'd' }); };
  464. /**
  465. * Serialize the body to an encoded string, where key-value pairs (separated by `=`) are
  466. * separated by `&`s.
  467. */
  468. HttpParams.prototype.toString = function () {
  469. var _this = this;
  470. this.init();
  471. return this.keys()
  472. .map(function (key) {
  473. var eKey = _this.encoder.encodeKey(key);
  474. return _this.map.get(key).map(function (value) { return eKey + '=' + _this.encoder.encodeValue(value); })
  475. .join('&');
  476. })
  477. .join('&');
  478. };
  479. HttpParams.prototype.clone = function (update) {
  480. var clone = new HttpParams({ encoder: this.encoder });
  481. clone.cloneFrom = this.cloneFrom || this;
  482. clone.updates = (this.updates || []).concat([update]);
  483. return clone;
  484. };
  485. HttpParams.prototype.init = function () {
  486. var _this = this;
  487. if (this.map === null) {
  488. this.map = new Map();
  489. }
  490. if (this.cloneFrom !== null) {
  491. this.cloneFrom.init();
  492. this.cloneFrom.keys().forEach(function (key) { return _this.map.set(key, _this.cloneFrom.map.get(key)); });
  493. this.updates.forEach(function (update) {
  494. switch (update.op) {
  495. case 'a':
  496. case 's':
  497. var base = (update.op === 'a' ? _this.map.get(update.param) : undefined) || [];
  498. base.push(update.value);
  499. _this.map.set(update.param, base);
  500. break;
  501. case 'd':
  502. if (update.value !== undefined) {
  503. var base_1 = _this.map.get(update.param) || [];
  504. var idx = base_1.indexOf(update.value);
  505. if (idx !== -1) {
  506. base_1.splice(idx, 1);
  507. }
  508. if (base_1.length > 0) {
  509. _this.map.set(update.param, base_1);
  510. }
  511. else {
  512. _this.map.delete(update.param);
  513. }
  514. }
  515. else {
  516. _this.map.delete(update.param);
  517. break;
  518. }
  519. }
  520. });
  521. this.cloneFrom = this.updates = null;
  522. }
  523. };
  524. return HttpParams;
  525. }());
  526. /**
  527. * @license
  528. * Copyright Google Inc. All Rights Reserved.
  529. *
  530. * Use of this source code is governed by an MIT-style license that can be
  531. * found in the LICENSE file at https://angular.io/license
  532. */
  533. /**
  534. * Determine whether the given HTTP method may include a body.
  535. */
  536. function mightHaveBody(method) {
  537. switch (method) {
  538. case 'DELETE':
  539. case 'GET':
  540. case 'HEAD':
  541. case 'OPTIONS':
  542. case 'JSONP':
  543. return false;
  544. default:
  545. return true;
  546. }
  547. }
  548. /**
  549. * Safely assert whether the given value is an ArrayBuffer.
  550. *
  551. * In some execution environments ArrayBuffer is not defined.
  552. */
  553. function isArrayBuffer(value) {
  554. return typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer;
  555. }
  556. /**
  557. * Safely assert whether the given value is a Blob.
  558. *
  559. * In some execution environments Blob is not defined.
  560. */
  561. function isBlob(value) {
  562. return typeof Blob !== 'undefined' && value instanceof Blob;
  563. }
  564. /**
  565. * Safely assert whether the given value is a FormData instance.
  566. *
  567. * In some execution environments FormData is not defined.
  568. */
  569. function isFormData(value) {
  570. return typeof FormData !== 'undefined' && value instanceof FormData;
  571. }
  572. /**
  573. * An outgoing HTTP request with an optional typed body.
  574. *
  575. * `HttpRequest` represents an outgoing request, including URL, method,
  576. * headers, body, and other request configuration options. Instances should be
  577. * assumed to be immutable. To modify a `HttpRequest`, the `clone`
  578. * method should be used.
  579. *
  580. * @publicApi
  581. */
  582. var HttpRequest = /** @class */ (function () {
  583. function HttpRequest(method, url, third, fourth) {
  584. this.url = url;
  585. /**
  586. * The request body, or `null` if one isn't set.
  587. *
  588. * Bodies are not enforced to be immutable, as they can include a reference to any
  589. * user-defined data type. However, interceptors should take care to preserve
  590. * idempotence by treating them as such.
  591. */
  592. this.body = null;
  593. /**
  594. * Whether this request should be made in a way that exposes progress events.
  595. *
  596. * Progress events are expensive (change detection runs on each event) and so
  597. * they should only be requested if the consumer intends to monitor them.
  598. */
  599. this.reportProgress = false;
  600. /**
  601. * Whether this request should be sent with outgoing credentials (cookies).
  602. */
  603. this.withCredentials = false;
  604. /**
  605. * The expected response type of the server.
  606. *
  607. * This is used to parse the response appropriately before returning it to
  608. * the requestee.
  609. */
  610. this.responseType = 'json';
  611. this.method = method.toUpperCase();
  612. // Next, need to figure out which argument holds the HttpRequestInit
  613. // options, if any.
  614. var options;
  615. // Check whether a body argument is expected. The only valid way to omit
  616. // the body argument is to use a known no-body method like GET.
  617. if (mightHaveBody(this.method) || !!fourth) {
  618. // Body is the third argument, options are the fourth.
  619. this.body = (third !== undefined) ? third : null;
  620. options = fourth;
  621. }
  622. else {
  623. // No body required, options are the third argument. The body stays null.
  624. options = third;
  625. }
  626. // If options have been passed, interpret them.
  627. if (options) {
  628. // Normalize reportProgress and withCredentials.
  629. this.reportProgress = !!options.reportProgress;
  630. this.withCredentials = !!options.withCredentials;
  631. // Override default response type of 'json' if one is provided.
  632. if (!!options.responseType) {
  633. this.responseType = options.responseType;
  634. }
  635. // Override headers if they're provided.
  636. if (!!options.headers) {
  637. this.headers = options.headers;
  638. }
  639. if (!!options.params) {
  640. this.params = options.params;
  641. }
  642. }
  643. // If no headers have been passed in, construct a new HttpHeaders instance.
  644. if (!this.headers) {
  645. this.headers = new HttpHeaders();
  646. }
  647. // If no parameters have been passed in, construct a new HttpUrlEncodedParams instance.
  648. if (!this.params) {
  649. this.params = new HttpParams();
  650. this.urlWithParams = url;
  651. }
  652. else {
  653. // Encode the parameters to a string in preparation for inclusion in the URL.
  654. var params = this.params.toString();
  655. if (params.length === 0) {
  656. // No parameters, the visible URL is just the URL given at creation time.
  657. this.urlWithParams = url;
  658. }
  659. else {
  660. // Does the URL already have query parameters? Look for '?'.
  661. var qIdx = url.indexOf('?');
  662. // There are 3 cases to handle:
  663. // 1) No existing parameters -> append '?' followed by params.
  664. // 2) '?' exists and is followed by existing query string ->
  665. // append '&' followed by params.
  666. // 3) '?' exists at the end of the url -> append params directly.
  667. // This basically amounts to determining the character, if any, with
  668. // which to join the URL and parameters.
  669. var sep = qIdx === -1 ? '?' : (qIdx < url.length - 1 ? '&' : '');
  670. this.urlWithParams = url + sep + params;
  671. }
  672. }
  673. }
  674. /**
  675. * Transform the free-form body into a serialized format suitable for
  676. * transmission to the server.
  677. */
  678. HttpRequest.prototype.serializeBody = function () {
  679. // If no body is present, no need to serialize it.
  680. if (this.body === null) {
  681. return null;
  682. }
  683. // Check whether the body is already in a serialized form. If so,
  684. // it can just be returned directly.
  685. if (isArrayBuffer(this.body) || isBlob(this.body) || isFormData(this.body) ||
  686. typeof this.body === 'string') {
  687. return this.body;
  688. }
  689. // Check whether the body is an instance of HttpUrlEncodedParams.
  690. if (this.body instanceof HttpParams) {
  691. return this.body.toString();
  692. }
  693. // Check whether the body is an object or array, and serialize with JSON if so.
  694. if (typeof this.body === 'object' || typeof this.body === 'boolean' ||
  695. Array.isArray(this.body)) {
  696. return JSON.stringify(this.body);
  697. }
  698. // Fall back on toString() for everything else.
  699. return this.body.toString();
  700. };
  701. /**
  702. * Examine the body and attempt to infer an appropriate MIME type
  703. * for it.
  704. *
  705. * If no such type can be inferred, this method will return `null`.
  706. */
  707. HttpRequest.prototype.detectContentTypeHeader = function () {
  708. // An empty body has no content type.
  709. if (this.body === null) {
  710. return null;
  711. }
  712. // FormData bodies rely on the browser's content type assignment.
  713. if (isFormData(this.body)) {
  714. return null;
  715. }
  716. // Blobs usually have their own content type. If it doesn't, then
  717. // no type can be inferred.
  718. if (isBlob(this.body)) {
  719. return this.body.type || null;
  720. }
  721. // Array buffers have unknown contents and thus no type can be inferred.
  722. if (isArrayBuffer(this.body)) {
  723. return null;
  724. }
  725. // Technically, strings could be a form of JSON data, but it's safe enough
  726. // to assume they're plain strings.
  727. if (typeof this.body === 'string') {
  728. return 'text/plain';
  729. }
  730. // `HttpUrlEncodedParams` has its own content-type.
  731. if (this.body instanceof HttpParams) {
  732. return 'application/x-www-form-urlencoded;charset=UTF-8';
  733. }
  734. // Arrays, objects, and numbers will be encoded as JSON.
  735. if (typeof this.body === 'object' || typeof this.body === 'number' ||
  736. Array.isArray(this.body)) {
  737. return 'application/json';
  738. }
  739. // No type could be inferred.
  740. return null;
  741. };
  742. HttpRequest.prototype.clone = function (update) {
  743. if (update === void 0) { update = {}; }
  744. // For method, url, and responseType, take the current value unless
  745. // it is overridden in the update hash.
  746. var method = update.method || this.method;
  747. var url = update.url || this.url;
  748. var responseType = update.responseType || this.responseType;
  749. // The body is somewhat special - a `null` value in update.body means
  750. // whatever current body is present is being overridden with an empty
  751. // body, whereas an `undefined` value in update.body implies no
  752. // override.
  753. var body = (update.body !== undefined) ? update.body : this.body;
  754. // Carefully handle the boolean options to differentiate between
  755. // `false` and `undefined` in the update args.
  756. var withCredentials = (update.withCredentials !== undefined) ? update.withCredentials : this.withCredentials;
  757. var reportProgress = (update.reportProgress !== undefined) ? update.reportProgress : this.reportProgress;
  758. // Headers and params may be appended to if `setHeaders` or
  759. // `setParams` are used.
  760. var headers = update.headers || this.headers;
  761. var params = update.params || this.params;
  762. // Check whether the caller has asked to add headers.
  763. if (update.setHeaders !== undefined) {
  764. // Set every requested header.
  765. headers =
  766. Object.keys(update.setHeaders)
  767. .reduce(function (headers, name) { return headers.set(name, update.setHeaders[name]); }, headers);
  768. }
  769. // Check whether the caller has asked to set params.
  770. if (update.setParams) {
  771. // Set every requested param.
  772. params = Object.keys(update.setParams)
  773. .reduce(function (params, param) { return params.set(param, update.setParams[param]); }, params);
  774. }
  775. // Finally, construct the new HttpRequest using the pieces from above.
  776. return new HttpRequest(method, url, body, {
  777. params: params, headers: headers, reportProgress: reportProgress, responseType: responseType, withCredentials: withCredentials,
  778. });
  779. };
  780. return HttpRequest;
  781. }());
  782. /**
  783. * @license
  784. * Copyright Google Inc. All Rights Reserved.
  785. *
  786. * Use of this source code is governed by an MIT-style license that can be
  787. * found in the LICENSE file at https://angular.io/license
  788. */
  789. (function (HttpEventType) {
  790. /**
  791. * The request was sent out over the wire.
  792. */
  793. HttpEventType[HttpEventType["Sent"] = 0] = "Sent";
  794. /**
  795. * An upload progress event was received.
  796. */
  797. HttpEventType[HttpEventType["UploadProgress"] = 1] = "UploadProgress";
  798. /**
  799. * The response status code and headers were received.
  800. */
  801. HttpEventType[HttpEventType["ResponseHeader"] = 2] = "ResponseHeader";
  802. /**
  803. * A download progress event was received.
  804. */
  805. HttpEventType[HttpEventType["DownloadProgress"] = 3] = "DownloadProgress";
  806. /**
  807. * The full response including the body was received.
  808. */
  809. HttpEventType[HttpEventType["Response"] = 4] = "Response";
  810. /**
  811. * A custom event from an interceptor or a backend.
  812. */
  813. HttpEventType[HttpEventType["User"] = 5] = "User";
  814. })(exports.HttpEventType || (exports.HttpEventType = {}));
  815. /**
  816. * Base class for both `HttpResponse` and `HttpHeaderResponse`.
  817. *
  818. * @publicApi
  819. */
  820. var HttpResponseBase = /** @class */ (function () {
  821. /**
  822. * Super-constructor for all responses.
  823. *
  824. * The single parameter accepted is an initialization hash. Any properties
  825. * of the response passed there will override the default values.
  826. */
  827. function HttpResponseBase(init, defaultStatus, defaultStatusText) {
  828. if (defaultStatus === void 0) { defaultStatus = 200; }
  829. if (defaultStatusText === void 0) { defaultStatusText = 'OK'; }
  830. // If the hash has values passed, use them to initialize the response.
  831. // Otherwise use the default values.
  832. this.headers = init.headers || new HttpHeaders();
  833. this.status = init.status !== undefined ? init.status : defaultStatus;
  834. this.statusText = init.statusText || defaultStatusText;
  835. this.url = init.url || null;
  836. // Cache the ok value to avoid defining a getter.
  837. this.ok = this.status >= 200 && this.status < 300;
  838. }
  839. return HttpResponseBase;
  840. }());
  841. /**
  842. * A partial HTTP response which only includes the status and header data,
  843. * but no response body.
  844. *
  845. * `HttpHeaderResponse` is a `HttpEvent` available on the response
  846. * event stream, only when progress events are requested.
  847. *
  848. * @publicApi
  849. */
  850. var HttpHeaderResponse = /** @class */ (function (_super) {
  851. __extends(HttpHeaderResponse, _super);
  852. /**
  853. * Create a new `HttpHeaderResponse` with the given parameters.
  854. */
  855. function HttpHeaderResponse(init) {
  856. if (init === void 0) { init = {}; }
  857. var _this = _super.call(this, init) || this;
  858. _this.type = exports.HttpEventType.ResponseHeader;
  859. return _this;
  860. }
  861. /**
  862. * Copy this `HttpHeaderResponse`, overriding its contents with the
  863. * given parameter hash.
  864. */
  865. HttpHeaderResponse.prototype.clone = function (update) {
  866. if (update === void 0) { update = {}; }
  867. // Perform a straightforward initialization of the new HttpHeaderResponse,
  868. // overriding the current parameters with new ones if given.
  869. return new HttpHeaderResponse({
  870. headers: update.headers || this.headers,
  871. status: update.status !== undefined ? update.status : this.status,
  872. statusText: update.statusText || this.statusText,
  873. url: update.url || this.url || undefined,
  874. });
  875. };
  876. return HttpHeaderResponse;
  877. }(HttpResponseBase));
  878. /**
  879. * A full HTTP response, including a typed response body (which may be `null`
  880. * if one was not returned).
  881. *
  882. * `HttpResponse` is a `HttpEvent` available on the response event
  883. * stream.
  884. *
  885. * @publicApi
  886. */
  887. var HttpResponse = /** @class */ (function (_super) {
  888. __extends(HttpResponse, _super);
  889. /**
  890. * Construct a new `HttpResponse`.
  891. */
  892. function HttpResponse(init) {
  893. if (init === void 0) { init = {}; }
  894. var _this = _super.call(this, init) || this;
  895. _this.type = exports.HttpEventType.Response;
  896. _this.body = init.body !== undefined ? init.body : null;
  897. return _this;
  898. }
  899. HttpResponse.prototype.clone = function (update) {
  900. if (update === void 0) { update = {}; }
  901. return new HttpResponse({
  902. body: (update.body !== undefined) ? update.body : this.body,
  903. headers: update.headers || this.headers,
  904. status: (update.status !== undefined) ? update.status : this.status,
  905. statusText: update.statusText || this.statusText,
  906. url: update.url || this.url || undefined,
  907. });
  908. };
  909. return HttpResponse;
  910. }(HttpResponseBase));
  911. /**
  912. * A response that represents an error or failure, either from a
  913. * non-successful HTTP status, an error while executing the request,
  914. * or some other failure which occurred during the parsing of the response.
  915. *
  916. * Any error returned on the `Observable` response stream will be
  917. * wrapped in an `HttpErrorResponse` to provide additional context about
  918. * the state of the HTTP layer when the error occurred. The error property
  919. * will contain either a wrapped Error object or the error response returned
  920. * from the server.
  921. *
  922. * @publicApi
  923. */
  924. var HttpErrorResponse = /** @class */ (function (_super) {
  925. __extends(HttpErrorResponse, _super);
  926. function HttpErrorResponse(init) {
  927. var _this =
  928. // Initialize with a default status of 0 / Unknown Error.
  929. _super.call(this, init, 0, 'Unknown Error') || this;
  930. _this.name = 'HttpErrorResponse';
  931. /**
  932. * Errors are never okay, even when the status code is in the 2xx success range.
  933. */
  934. _this.ok = false;
  935. // If the response was successful, then this was a parse error. Otherwise, it was
  936. // a protocol-level failure of some sort. Either the request failed in transit
  937. // or the server returned an unsuccessful status code.
  938. if (_this.status >= 200 && _this.status < 300) {
  939. _this.message = "Http failure during parsing for " + (init.url || '(unknown url)');
  940. }
  941. else {
  942. _this.message =
  943. "Http failure response for " + (init.url || '(unknown url)') + ": " + init.status + " " + init.statusText;
  944. }
  945. _this.error = init.error || null;
  946. return _this;
  947. }
  948. return HttpErrorResponse;
  949. }(HttpResponseBase));
  950. /**
  951. * @license
  952. * Copyright Google Inc. All Rights Reserved.
  953. *
  954. * Use of this source code is governed by an MIT-style license that can be
  955. * found in the LICENSE file at https://angular.io/license
  956. */
  957. /**
  958. * Constructs an instance of `HttpRequestOptions<T>` from a source `HttpMethodOptions` and
  959. * the given `body`. This function clones the object and adds the body.
  960. */
  961. function addBody(options, body) {
  962. return {
  963. body: body,
  964. headers: options.headers,
  965. observe: options.observe,
  966. params: options.params,
  967. reportProgress: options.reportProgress,
  968. responseType: options.responseType,
  969. withCredentials: options.withCredentials,
  970. };
  971. }
  972. /**
  973. * Performs HTTP requests.
  974. *
  975. * `HttpClient` is available as an injectable class, with methods to perform HTTP requests.
  976. * Each request method has multiple signatures, and the return type varies based on
  977. * the signature that is called (mainly the values of `observe` and `responseType`).
  978. *
  979. *
  980. * @see [HTTP Guide](guide/http)
  981. *
  982. *
  983. * @usageNotes
  984. * Sample HTTP requests for the [Tour of Heroes](/tutorial/toh-pt0) application.
  985. *
  986. * ### HTTP Request Example
  987. *
  988. * ```
  989. * // GET heroes whose name contains search term
  990. * searchHeroes(term: string): observable<Hero[]>{
  991. *
  992. * const params = new HttpParams({fromString: 'name=term'});
  993. * return this.httpClient.request('GET', this.heroesUrl, {responseType:'json', params});
  994. * }
  995. * ```
  996. * ### JSONP Example
  997. * ```
  998. * requestJsonp(url, callback = 'callback') {
  999. * return this.httpClient.jsonp(this.heroesURL, callback);
  1000. * }
  1001. * ```
  1002. *
  1003. *
  1004. * ### PATCH Example
  1005. * ```
  1006. * // PATCH one of the heroes' name
  1007. * patchHero (id: number, heroName: string): Observable<{}> {
  1008. * const url = `${this.heroesUrl}/${id}`; // PATCH api/heroes/42
  1009. * return this.httpClient.patch(url, {name: heroName}, httpOptions)
  1010. * .pipe(catchError(this.handleError('patchHero')));
  1011. * }
  1012. * ```
  1013. *
  1014. * @publicApi
  1015. */
  1016. var HttpClient = /** @class */ (function () {
  1017. function HttpClient(handler) {
  1018. this.handler = handler;
  1019. }
  1020. /**
  1021. * Constructs an observable for a generic HTTP request that, when subscribed,
  1022. * fires the request through the chain of registered interceptors and on to the
  1023. * server.
  1024. *
  1025. * You can pass an `HttpRequest` directly as the only parameter. In this case,
  1026. * the call returns an observable of the raw `HttpEvent` stream.
  1027. *
  1028. * Alternatively you can pass an HTTP method as the first parameter,
  1029. * a URL string as the second, and an options hash containing the request body as the third.
  1030. * See `addBody()`. In this case, the specified `responseType` and `observe` options determine the
  1031. * type of returned observable.
  1032. * * The `responseType` value determines how a successful response body is parsed.
  1033. * * If `responseType` is the default `json`, you can pass a type interface for the resulting
  1034. * object as a type parameter to the call.
  1035. *
  1036. * The `observe` value determines the return type, according to what you are interested in
  1037. * observing.
  1038. * * An `observe` value of events returns an observable of the raw `HttpEvent` stream, including
  1039. * progress events by default.
  1040. * * An `observe` value of response returns an observable of `HttpResponse<T>`,
  1041. * where the `T` parameter depends on the `responseType` and any optionally provided type
  1042. * parameter.
  1043. * * An `observe` value of body returns an observable of `<T>` with the same `T` body type.
  1044. *
  1045. */
  1046. HttpClient.prototype.request = function (first, url, options) {
  1047. var _this = this;
  1048. if (options === void 0) { options = {}; }
  1049. var req;
  1050. // First, check whether the primary argument is an instance of `HttpRequest`.
  1051. if (first instanceof HttpRequest) {
  1052. // It is. The other arguments must be undefined (per the signatures) and can be
  1053. // ignored.
  1054. req = first;
  1055. }
  1056. else {
  1057. // It's a string, so it represents a URL. Construct a request based on it,
  1058. // and incorporate the remaining arguments (assuming `GET` unless a method is
  1059. // provided.
  1060. // Figure out the headers.
  1061. var headers = undefined;
  1062. if (options.headers instanceof HttpHeaders) {
  1063. headers = options.headers;
  1064. }
  1065. else {
  1066. headers = new HttpHeaders(options.headers);
  1067. }
  1068. // Sort out parameters.
  1069. var params = undefined;
  1070. if (!!options.params) {
  1071. if (options.params instanceof HttpParams) {
  1072. params = options.params;
  1073. }
  1074. else {
  1075. params = new HttpParams({ fromObject: options.params });
  1076. }
  1077. }
  1078. // Construct the request.
  1079. req = new HttpRequest(first, url, (options.body !== undefined ? options.body : null), {
  1080. headers: headers,
  1081. params: params,
  1082. reportProgress: options.reportProgress,
  1083. // By default, JSON is assumed to be returned for all calls.
  1084. responseType: options.responseType || 'json',
  1085. withCredentials: options.withCredentials,
  1086. });
  1087. }
  1088. // Start with an Observable.of() the initial request, and run the handler (which
  1089. // includes all interceptors) inside a concatMap(). This way, the handler runs
  1090. // inside an Observable chain, which causes interceptors to be re-run on every
  1091. // subscription (this also makes retries re-run the handler, including interceptors).
  1092. var events$ = rxjs.of(req).pipe(operators.concatMap(function (req) { return _this.handler.handle(req); }));
  1093. // If coming via the API signature which accepts a previously constructed HttpRequest,
  1094. // the only option is to get the event stream. Otherwise, return the event stream if
  1095. // that is what was requested.
  1096. if (first instanceof HttpRequest || options.observe === 'events') {
  1097. return events$;
  1098. }
  1099. // The requested stream contains either the full response or the body. In either
  1100. // case, the first step is to filter the event stream to extract a stream of
  1101. // responses(s).
  1102. var res$ = events$.pipe(operators.filter(function (event) { return event instanceof HttpResponse; }));
  1103. // Decide which stream to return.
  1104. switch (options.observe || 'body') {
  1105. case 'body':
  1106. // The requested stream is the body. Map the response stream to the response
  1107. // body. This could be done more simply, but a misbehaving interceptor might
  1108. // transform the response body into a different format and ignore the requested
  1109. // responseType. Guard against this by validating that the response is of the
  1110. // requested type.
  1111. switch (req.responseType) {
  1112. case 'arraybuffer':
  1113. return res$.pipe(operators.map(function (res) {
  1114. // Validate that the body is an ArrayBuffer.
  1115. if (res.body !== null && !(res.body instanceof ArrayBuffer)) {
  1116. throw new Error('Response is not an ArrayBuffer.');
  1117. }
  1118. return res.body;
  1119. }));
  1120. case 'blob':
  1121. return res$.pipe(operators.map(function (res) {
  1122. // Validate that the body is a Blob.
  1123. if (res.body !== null && !(res.body instanceof Blob)) {
  1124. throw new Error('Response is not a Blob.');
  1125. }
  1126. return res.body;
  1127. }));
  1128. case 'text':
  1129. return res$.pipe(operators.map(function (res) {
  1130. // Validate that the body is a string.
  1131. if (res.body !== null && typeof res.body !== 'string') {
  1132. throw new Error('Response is not a string.');
  1133. }
  1134. return res.body;
  1135. }));
  1136. case 'json':
  1137. default:
  1138. // No validation needed for JSON responses, as they can be of any type.
  1139. return res$.pipe(operators.map(function (res) { return res.body; }));
  1140. }
  1141. case 'response':
  1142. // The response stream was requested directly, so return it.
  1143. return res$;
  1144. default:
  1145. // Guard against new future observe types being added.
  1146. throw new Error("Unreachable: unhandled observe type " + options.observe + "}");
  1147. }
  1148. };
  1149. /**
  1150. * Constructs an observable that, when subscribed, causes the configured
  1151. * `DELETE` request to execute on the server. See the individual overloads for
  1152. * details on the return type.
  1153. *
  1154. * @param url The endpoint URL.
  1155. * @param options The HTTP options to send with the request.
  1156. *
  1157. */
  1158. HttpClient.prototype.delete = function (url, options) {
  1159. if (options === void 0) { options = {}; }
  1160. return this.request('DELETE', url, options);
  1161. };
  1162. /**
  1163. * Constructs an observable that, when subscribed, causes the configured
  1164. * `GET` request to execute on the server. See the individual overloads for
  1165. * details on the return type.
  1166. */
  1167. HttpClient.prototype.get = function (url, options) {
  1168. if (options === void 0) { options = {}; }
  1169. return this.request('GET', url, options);
  1170. };
  1171. /**
  1172. * Constructs an observable that, when subscribed, causes the configured
  1173. * `HEAD` request to execute on the server. The `HEAD` method returns
  1174. * meta information about the resource without transferring the
  1175. * resource itself. See the individual overloads for
  1176. * details on the return type.
  1177. */
  1178. HttpClient.prototype.head = function (url, options) {
  1179. if (options === void 0) { options = {}; }
  1180. return this.request('HEAD', url, options);
  1181. };
  1182. /**
  1183. * Constructs an `Observable` that, when subscribed, causes a request with the special method
  1184. * `JSONP` to be dispatched via the interceptor pipeline.
  1185. * The [JSONP pattern](https://en.wikipedia.org/wiki/JSONP) works around limitations of certain
  1186. * API endpoints that don't support newer,
  1187. * and preferable [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) protocol.
  1188. * JSONP treats the endpoint API as a JavaScript file and tricks the browser to process the
  1189. * requests even if the API endpoint is not located on the same domain (origin) as the client-side
  1190. * application making the request.
  1191. * The endpoint API must support JSONP callback for JSONP requests to work.
  1192. * The resource API returns the JSON response wrapped in a callback function.
  1193. * You can pass the callback function name as one of the query parameters.
  1194. * Note that JSONP requests can only be used with `GET` requests.
  1195. *
  1196. * @param url The resource URL.
  1197. * @param callbackParam The callback function name.
  1198. *
  1199. */
  1200. HttpClient.prototype.jsonp = function (url, callbackParam) {
  1201. return this.request('JSONP', url, {
  1202. params: new HttpParams().append(callbackParam, 'JSONP_CALLBACK'),
  1203. observe: 'body',
  1204. responseType: 'json',
  1205. });
  1206. };
  1207. /**
  1208. * Constructs an `Observable` that, when subscribed, causes the configured
  1209. * `OPTIONS` request to execute on the server. This method allows the client
  1210. * to determine the supported HTTP methods and other capabilites of an endpoint,
  1211. * without implying a resource action. See the individual overloads for
  1212. * details on the return type.
  1213. */
  1214. HttpClient.prototype.options = function (url, options) {
  1215. if (options === void 0) { options = {}; }
  1216. return this.request('OPTIONS', url, options);
  1217. };
  1218. /**
  1219. * Constructs an observable that, when subscribed, causes the configured
  1220. * `PATCH` request to execute on the server. See the individual overloads for
  1221. * details on the return type.
  1222. */
  1223. HttpClient.prototype.patch = function (url, body, options) {
  1224. if (options === void 0) { options = {}; }
  1225. return this.request('PATCH', url, addBody(options, body));
  1226. };
  1227. /**
  1228. * Constructs an observable that, when subscribed, causes the configured
  1229. * `POST` request to execute on the server. The server responds with the location of
  1230. * the replaced resource. See the individual overloads for
  1231. * details on the return type.
  1232. */
  1233. HttpClient.prototype.post = function (url, body, options) {
  1234. if (options === void 0) { options = {}; }
  1235. return this.request('POST', url, addBody(options, body));
  1236. };
  1237. /**
  1238. * Constructs an observable that, when subscribed, causes the configured
  1239. * `PUT` request to execute on the server. The `PUT` method replaces an existing resource
  1240. * with a new set of values.
  1241. * See the individual overloads for details on the return type.
  1242. */
  1243. HttpClient.prototype.put = function (url, body, options) {
  1244. if (options === void 0) { options = {}; }
  1245. return this.request('PUT', url, addBody(options, body));
  1246. };
  1247. HttpClient = __decorate([
  1248. core.Injectable(),
  1249. __metadata("design:paramtypes", [HttpHandler])
  1250. ], HttpClient);
  1251. return HttpClient;
  1252. }());
  1253. /**
  1254. * @license
  1255. * Copyright Google Inc. All Rights Reserved.
  1256. *
  1257. * Use of this source code is governed by an MIT-style license that can be
  1258. * found in the LICENSE file at https://angular.io/license
  1259. */
  1260. /**
  1261. * `HttpHandler` which applies an `HttpInterceptor` to an `HttpRequest`.
  1262. *
  1263. *
  1264. */
  1265. var HttpInterceptorHandler = /** @class */ (function () {
  1266. function HttpInterceptorHandler(next, interceptor) {
  1267. this.next = next;
  1268. this.interceptor = interceptor;
  1269. }
  1270. HttpInterceptorHandler.prototype.handle = function (req) {
  1271. return this.interceptor.intercept(req, this.next);
  1272. };
  1273. return HttpInterceptorHandler;
  1274. }());
  1275. /**
  1276. * A multi-provider token which represents the array of `HttpInterceptor`s that
  1277. * are registered.
  1278. *
  1279. * @publicApi
  1280. */
  1281. var HTTP_INTERCEPTORS = new core.InjectionToken('HTTP_INTERCEPTORS');
  1282. var NoopInterceptor = /** @class */ (function () {
  1283. function NoopInterceptor() {
  1284. }
  1285. NoopInterceptor.prototype.intercept = function (req, next) {
  1286. return next.handle(req);
  1287. };
  1288. NoopInterceptor = __decorate([
  1289. core.Injectable()
  1290. ], NoopInterceptor);
  1291. return NoopInterceptor;
  1292. }());
  1293. /**
  1294. * @license
  1295. * Copyright Google Inc. All Rights Reserved.
  1296. *
  1297. * Use of this source code is governed by an MIT-style license that can be
  1298. * found in the LICENSE file at https://angular.io/license
  1299. */
  1300. // Every request made through JSONP needs a callback name that's unique across the
  1301. // whole page. Each request is assigned an id and the callback name is constructed
  1302. // from that. The next id to be assigned is tracked in a global variable here that
  1303. // is shared among all applications on the page.
  1304. var nextRequestId = 0;
  1305. // Error text given when a JSONP script is injected, but doesn't invoke the callback
  1306. // passed in its URL.
  1307. var JSONP_ERR_NO_CALLBACK = 'JSONP injected script did not invoke callback.';
  1308. // Error text given when a request is passed to the JsonpClientBackend that doesn't
  1309. // have a request method JSONP.
  1310. var JSONP_ERR_WRONG_METHOD = 'JSONP requests must use JSONP request method.';
  1311. var JSONP_ERR_WRONG_RESPONSE_TYPE = 'JSONP requests must use Json response type.';
  1312. /**
  1313. * DI token/abstract type representing a map of JSONP callbacks.
  1314. *
  1315. * In the browser, this should always be the `window` object.
  1316. *
  1317. *
  1318. */
  1319. var JsonpCallbackContext = /** @class */ (function () {
  1320. function JsonpCallbackContext() {
  1321. }
  1322. return JsonpCallbackContext;
  1323. }());
  1324. /**
  1325. * `HttpBackend` that only processes `HttpRequest` with the JSONP method,
  1326. * by performing JSONP style requests.
  1327. *
  1328. * @publicApi
  1329. */
  1330. var JsonpClientBackend = /** @class */ (function () {
  1331. function JsonpClientBackend(callbackMap, document) {
  1332. this.callbackMap = callbackMap;
  1333. this.document = document;
  1334. }
  1335. /**
  1336. * Get the name of the next callback method, by incrementing the global `nextRequestId`.
  1337. */
  1338. JsonpClientBackend.prototype.nextCallback = function () { return "ng_jsonp_callback_" + nextRequestId++; };
  1339. /**
  1340. * Process a JSONP request and return an event stream of the results.
  1341. */
  1342. JsonpClientBackend.prototype.handle = function (req) {
  1343. var _this = this;
  1344. // Firstly, check both the method and response type. If either doesn't match
  1345. // then the request was improperly routed here and cannot be handled.
  1346. if (req.method !== 'JSONP') {
  1347. throw new Error(JSONP_ERR_WRONG_METHOD);
  1348. }
  1349. else if (req.responseType !== 'json') {
  1350. throw new Error(JSONP_ERR_WRONG_RESPONSE_TYPE);
  1351. }
  1352. // Everything else happens inside the Observable boundary.
  1353. return new rxjs.Observable(function (observer) {
  1354. // The first step to make a request is to generate the callback name, and replace the
  1355. // callback placeholder in the URL with the name. Care has to be taken here to ensure
  1356. // a trailing &, if matched, gets inserted back into the URL in the correct place.
  1357. var callback = _this.nextCallback();
  1358. var url = req.urlWithParams.replace(/=JSONP_CALLBACK(&|$)/, "=" + callback + "$1");
  1359. // Construct the <script> tag and point it at the URL.
  1360. var node = _this.document.createElement('script');
  1361. node.src = url;
  1362. // A JSONP request requires waiting for multiple callbacks. These variables
  1363. // are closed over and track state across those callbacks.
  1364. // The response object, if one has been received, or null otherwise.
  1365. var body = null;
  1366. // Whether the response callback has been called.
  1367. var finished = false;
  1368. // Whether the request has been cancelled (and thus any other callbacks)
  1369. // should be ignored.
  1370. var cancelled = false;
  1371. // Set the response callback in this.callbackMap (which will be the window
  1372. // object in the browser. The script being loaded via the <script> tag will
  1373. // eventually call this callback.
  1374. _this.callbackMap[callback] = function (data) {
  1375. // Data has been received from the JSONP script. Firstly, delete this callback.
  1376. delete _this.callbackMap[callback];
  1377. // Next, make sure the request wasn't cancelled in the meantime.
  1378. if (cancelled) {
  1379. return;
  1380. }
  1381. // Set state to indicate data was received.
  1382. body = data;
  1383. finished = true;
  1384. };
  1385. // cleanup() is a utility closure that removes the <script> from the page and
  1386. // the response callback from the window. This logic is used in both the
  1387. // success, error, and cancellation paths, so it's extracted out for convenience.
  1388. var cleanup = function () {
  1389. // Remove the <script> tag if it's still on the page.
  1390. if (node.parentNode) {
  1391. node.parentNode.removeChild(node);
  1392. }
  1393. // Remove the response callback from the callbackMap (window object in the
  1394. // browser).
  1395. delete _this.callbackMap[callback];
  1396. };
  1397. // onLoad() is the success callback which runs after the response callback
  1398. // if the JSONP script loads successfully. The event itself is unimportant.
  1399. // If something went wrong, onLoad() may run without the response callback
  1400. // having been invoked.
  1401. var onLoad = function (event) {
  1402. // Do nothing if the request has been cancelled.
  1403. if (cancelled) {
  1404. return;
  1405. }
  1406. // Cleanup the page.
  1407. cleanup();
  1408. // Check whether the response callback has run.
  1409. if (!finished) {
  1410. // It hasn't, something went wrong with the request. Return an error via
  1411. // the Observable error path. All JSONP errors have status 0.
  1412. observer.error(new HttpErrorResponse({
  1413. url: url,
  1414. status: 0,
  1415. statusText: 'JSONP Error',
  1416. error: new Error(JSONP_ERR_NO_CALLBACK),
  1417. }));
  1418. return;
  1419. }
  1420. // Success. body either contains the response body or null if none was
  1421. // returned.
  1422. observer.next(new HttpResponse({
  1423. body: body,
  1424. status: 200,
  1425. statusText: 'OK', url: url,
  1426. }));
  1427. // Complete the stream, the response is over.
  1428. observer.complete();
  1429. };
  1430. // onError() is the error callback, which runs if the script returned generates
  1431. // a Javascript error. It emits the error via the Observable error channel as
  1432. // a HttpErrorResponse.
  1433. var onError = function (error) {
  1434. // If the request was already cancelled, no need to emit anything.
  1435. if (cancelled) {
  1436. return;
  1437. }
  1438. cleanup();
  1439. // Wrap the error in a HttpErrorResponse.
  1440. observer.error(new HttpErrorResponse({
  1441. error: error,
  1442. status: 0,
  1443. statusText: 'JSONP Error', url: url,
  1444. }));
  1445. };
  1446. // Subscribe to both the success (load) and error events on the <script> tag,
  1447. // and add it to the page.
  1448. node.addEventListener('load', onLoad);
  1449. node.addEventListener('error', onError);
  1450. _this.document.body.appendChild(node);
  1451. // The request has now been successfully sent.
  1452. observer.next({ type: exports.HttpEventType.Sent });
  1453. // Cancellation handler.
  1454. return function () {
  1455. // Track the cancellation so event listeners won't do anything even if already scheduled.
  1456. cancelled = true;
  1457. // Remove the event listeners so they won't run if the events later fire.
  1458. node.removeEventListener('load', onLoad);
  1459. node.removeEventListener('error', onError);
  1460. // And finally, clean up the page.
  1461. cleanup();
  1462. };
  1463. });
  1464. };
  1465. JsonpClientBackend = __decorate([
  1466. core.Injectable(),
  1467. __param(1, core.Inject(common.DOCUMENT)),
  1468. __metadata("design:paramtypes", [JsonpCallbackContext, Object])
  1469. ], JsonpClientBackend);
  1470. return JsonpClientBackend;
  1471. }());
  1472. /**
  1473. * An `HttpInterceptor` which identifies requests with the method JSONP and
  1474. * shifts them to the `JsonpClientBackend`.
  1475. *
  1476. * @publicApi
  1477. */
  1478. var JsonpInterceptor = /** @class */ (function () {
  1479. function JsonpInterceptor(jsonp) {
  1480. this.jsonp = jsonp;
  1481. }
  1482. JsonpInterceptor.prototype.intercept = function (req, next) {
  1483. if (req.method === 'JSONP') {
  1484. return this.jsonp.handle(req);
  1485. }
  1486. // Fall through for normal HTTP requests.
  1487. return next.handle(req);
  1488. };
  1489. JsonpInterceptor = __decorate([
  1490. core.Injectable(),
  1491. __metadata("design:paramtypes", [JsonpClientBackend])
  1492. ], JsonpInterceptor);
  1493. return JsonpInterceptor;
  1494. }());
  1495. /**
  1496. * @license
  1497. * Copyright Google Inc. All Rights Reserved.
  1498. *
  1499. * Use of this source code is governed by an MIT-style license that can be
  1500. * found in the LICENSE file at https://angular.io/license
  1501. */
  1502. var XSSI_PREFIX = /^\)\]\}',?\n/;
  1503. /**
  1504. * Determine an appropriate URL for the response, by checking either
  1505. * XMLHttpRequest.responseURL or the X-Request-URL header.
  1506. */
  1507. function getResponseUrl(xhr) {
  1508. if ('responseURL' in xhr && xhr.responseURL) {
  1509. return xhr.responseURL;
  1510. }
  1511. if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
  1512. return xhr.getResponseHeader('X-Request-URL');
  1513. }
  1514. return null;
  1515. }
  1516. /**
  1517. * A wrapper around the `XMLHttpRequest` constructor.
  1518. *
  1519. * @publicApi
  1520. */
  1521. var XhrFactory = /** @class */ (function () {
  1522. function XhrFactory() {
  1523. }
  1524. return XhrFactory;
  1525. }());
  1526. /**
  1527. * A factory for @{link HttpXhrBackend} that uses the `XMLHttpRequest` browser API.
  1528. *
  1529. *
  1530. */
  1531. var BrowserXhr = /** @class */ (function () {
  1532. function BrowserXhr() {
  1533. }
  1534. BrowserXhr.prototype.build = function () { return (new XMLHttpRequest()); };
  1535. BrowserXhr = __decorate([
  1536. core.Injectable(),
  1537. __metadata("design:paramtypes", [])
  1538. ], BrowserXhr);
  1539. return BrowserXhr;
  1540. }());
  1541. /**
  1542. * An `HttpBackend` which uses the XMLHttpRequest API to send
  1543. * requests to a backend server.
  1544. *
  1545. * @publicApi
  1546. */
  1547. var HttpXhrBackend = /** @class */ (function () {
  1548. function HttpXhrBackend(xhrFactory) {
  1549. this.xhrFactory = xhrFactory;
  1550. }
  1551. /**
  1552. * Process a request and return a stream of response events.
  1553. */
  1554. HttpXhrBackend.prototype.handle = function (req) {
  1555. var _this = this;
  1556. // Quick check to give a better error message when a user attempts to use
  1557. // HttpClient.jsonp() without installing the JsonpClientModule
  1558. if (req.method === 'JSONP') {
  1559. throw new Error("Attempted to construct Jsonp request without JsonpClientModule installed.");
  1560. }
  1561. // Everything happens on Observable subscription.
  1562. return new rxjs.Observable(function (observer) {
  1563. // Start by setting up the XHR object with request method, URL, and withCredentials flag.
  1564. var xhr = _this.xhrFactory.build();
  1565. xhr.open(req.method, req.urlWithParams);
  1566. if (!!req.withCredentials) {
  1567. xhr.withCredentials = true;
  1568. }
  1569. // Add all the requested headers.
  1570. req.headers.forEach(function (name, values) { return xhr.setRequestHeader(name, values.join(',')); });
  1571. // Add an Accept header if one isn't present already.
  1572. if (!req.headers.has('Accept')) {
  1573. xhr.setRequestHeader('Accept', 'application/json, text/plain, */*');
  1574. }
  1575. // Auto-detect the Content-Type header if one isn't present already.
  1576. if (!req.headers.has('Content-Type')) {
  1577. var detectedType = req.detectContentTypeHeader();
  1578. // Sometimes Content-Type detection fails.
  1579. if (detectedType !== null) {
  1580. xhr.setRequestHeader('Content-Type', detectedType);
  1581. }
  1582. }
  1583. // Set the responseType if one was requested.
  1584. if (req.responseType) {
  1585. var responseType = req.responseType.toLowerCase();
  1586. // JSON responses need to be processed as text. This is because if the server
  1587. // returns an XSSI-prefixed JSON response, the browser will fail to parse it,
  1588. // xhr.response will be null, and xhr.responseText cannot be accessed to
  1589. // retrieve the prefixed JSON data in order to strip the prefix. Thus, all JSON
  1590. // is parsed by first requesting text and then applying JSON.parse.
  1591. xhr.responseType = ((responseType !== 'json') ? responseType : 'text');
  1592. }
  1593. // Serialize the request body if one is present. If not, this will be set to null.
  1594. var reqBody = req.serializeBody();
  1595. // If progress events are enabled, response headers will be delivered
  1596. // in two events - the HttpHeaderResponse event and the full HttpResponse
  1597. // event. However, since response headers don't change in between these
  1598. // two events, it doesn't make sense to parse them twice. So headerResponse
  1599. // caches the data extracted from the response whenever it's first parsed,
  1600. // to ensure parsing isn't duplicated.
  1601. var headerResponse = null;
  1602. // partialFromXhr extracts the HttpHeaderResponse from the current XMLHttpRequest
  1603. // state, and memoizes it into headerResponse.
  1604. var partialFromXhr = function () {
  1605. if (headerResponse !== null) {
  1606. return headerResponse;
  1607. }
  1608. // Read status and normalize an IE9 bug (http://bugs.jquery.com/ticket/1450).
  1609. var status = xhr.status === 1223 ? 204 : xhr.status;
  1610. var statusText = xhr.statusText || 'OK';
  1611. // Parse headers from XMLHttpRequest - this step is lazy.
  1612. var headers = new HttpHeaders(xhr.getAllResponseHeaders());
  1613. // Read the response URL from the XMLHttpResponse instance and fall back on the
  1614. // request URL.
  1615. var url = getResponseUrl(xhr) || req.url;
  1616. // Construct the HttpHeaderResponse and memoize it.
  1617. headerResponse = new HttpHeaderResponse({ headers: headers, status: status, statusText: statusText, url: url });
  1618. return headerResponse;
  1619. };
  1620. // Next, a few closures are defined for the various events which XMLHttpRequest can
  1621. // emit. This allows them to be unregistered as event listeners later.
  1622. // First up is the load event, which represents a response being fully available.
  1623. var onLoad = function () {
  1624. // Read response state from the memoized partial data.
  1625. var _a = partialFromXhr(), headers = _a.headers, status = _a.status, statusText = _a.statusText, url = _a.url;
  1626. // The body will be read out if present.
  1627. var body = null;
  1628. if (status !== 204) {
  1629. // Use XMLHttpRequest.response if set, responseText otherwise.
  1630. body = (typeof xhr.response === 'undefined') ? xhr.responseText : xhr.response;
  1631. }
  1632. // Normalize another potential bug (this one comes from CORS).
  1633. if (status === 0) {
  1634. status = !!body ? 200 : 0;
  1635. }
  1636. // ok determines whether the response will be transmitted on the event or
  1637. // error channel. Unsuccessful status codes (not 2xx) will always be errors,
  1638. // but a successful status code can still result in an error if the user
  1639. // asked for JSON data and the body cannot be parsed as such.
  1640. var ok = status >= 200 && status < 300;
  1641. // Check whether the body needs to be parsed as JSON (in many cases the browser
  1642. // will have done that already).
  1643. if (req.responseType === 'json' && typeof body === 'string') {
  1644. // Save the original body, before attempting XSSI prefix stripping.
  1645. var originalBody = body;
  1646. body = body.replace(XSSI_PREFIX, '');
  1647. try {
  1648. // Attempt the parse. If it fails, a parse error should be delivered to the user.
  1649. body = body !== '' ? JSON.parse(body) : null;
  1650. }
  1651. catch (error) {
  1652. // Since the JSON.parse failed, it's reasonable to assume this might not have been a
  1653. // JSON response. Restore the original body (including any XSSI prefix) to deliver
  1654. // a better error response.
  1655. body = originalBody;
  1656. // If this was an error request to begin with, leave it as a string, it probably
  1657. // just isn't JSON. Otherwise, deliver the parsing error to the user.
  1658. if (ok) {
  1659. // Even though the response status was 2xx, this is still an error.
  1660. ok = false;
  1661. // The parse error contains the text of the body that failed to parse.
  1662. body = { error: error, text: body };
  1663. }
  1664. }
  1665. }
  1666. if (ok) {
  1667. // A successful response is delivered on the event stream.
  1668. observer.next(new HttpResponse({
  1669. body: body,
  1670. headers: headers,
  1671. status: status,
  1672. statusText: statusText,
  1673. url: url || undefined,
  1674. }));
  1675. // The full body has been received and delivered, no further events
  1676. // are possible. This request is complete.
  1677. observer.complete();
  1678. }
  1679. else {
  1680. // An unsuccessful request is delivered on the error channel.
  1681. observer.error(new HttpErrorResponse({
  1682. // The error in this case is the response body (error from the server).
  1683. error: body,
  1684. headers: headers,
  1685. status: status,
  1686. statusText: statusText,
  1687. url: url || undefined,
  1688. }));
  1689. }
  1690. };
  1691. // The onError callback is called when something goes wrong at the network level.
  1692. // Connection timeout, DNS error, offline, etc. These are actual errors, and are
  1693. // transmitted on the error channel.
  1694. var onError = function (error) {
  1695. var url = partialFromXhr().url;
  1696. var res = new HttpErrorResponse({
  1697. error: error,
  1698. status: xhr.status || 0,
  1699. statusText: xhr.statusText || 'Unknown Error',
  1700. url: url || undefined,
  1701. });
  1702. observer.error(res);
  1703. };
  1704. // The sentHeaders flag tracks whether the HttpResponseHeaders event
  1705. // has been sent on the stream. This is necessary to track if progress
  1706. // is enabled since the event will be sent on only the first download
  1707. // progerss event.
  1708. var sentHeaders = false;
  1709. // The download progress event handler, which is only registered if
  1710. // progress events are enabled.
  1711. var onDownProgress = function (event) {
  1712. // Send the HttpResponseHeaders event if it hasn't been sent already.
  1713. if (!sentHeaders) {
  1714. observer.next(partialFromXhr());
  1715. sentHeaders = true;
  1716. }
  1717. // Start building the download progress event to deliver on the response
  1718. // event stream.
  1719. var progressEvent = {
  1720. type: exports.HttpEventType.DownloadProgress,
  1721. loaded: event.loaded,
  1722. };
  1723. // Set the total number of bytes in the event if it's available.
  1724. if (event.lengthComputable) {
  1725. progressEvent.total = event.total;
  1726. }
  1727. // If the request was for text content and a partial response is
  1728. // available on XMLHttpRequest, include it in the progress event
  1729. // to allow for streaming reads.
  1730. if (req.responseType === 'text' && !!xhr.responseText) {
  1731. progressEvent.partialText = xhr.responseText;
  1732. }
  1733. // Finally, fire the event.
  1734. observer.next(progressEvent);
  1735. };
  1736. // The upload progress event handler, which is only registered if
  1737. // progress events are enabled.
  1738. var onUpProgress = function (event) {
  1739. // Upload progress events are simpler. Begin building the progress
  1740. // event.
  1741. var progress = {
  1742. type: exports.HttpEventType.UploadProgress,
  1743. loaded: event.loaded,
  1744. };
  1745. // If the total number of bytes being uploaded is available, include
  1746. // it.
  1747. if (event.lengthComputable) {
  1748. progress.total = event.total;
  1749. }
  1750. // Send the event.
  1751. observer.next(progress);
  1752. };
  1753. // By default, register for load and error events.
  1754. xhr.addEventListener('load', onLoad);
  1755. xhr.addEventListener('error', onError);
  1756. // Progress events are only enabled if requested.
  1757. if (req.reportProgress) {
  1758. // Download progress is always enabled if requested.
  1759. xhr.addEventListener('progress', onDownProgress);
  1760. // Upload progress depends on whether there is a body to upload.
  1761. if (reqBody !== null && xhr.upload) {
  1762. xhr.upload.addEventListener('progress', onUpProgress);
  1763. }
  1764. }
  1765. // Fire the request, and notify the event stream that it was fired.
  1766. xhr.send(reqBody);
  1767. observer.next({ type: exports.HttpEventType.Sent });
  1768. // This is the return from the Observable function, which is the
  1769. // request cancellation handler.
  1770. return function () {
  1771. // On a cancellation, remove all registered event listeners.
  1772. xhr.removeEventListener('error', onError);
  1773. xhr.removeEventListener('load', onLoad);
  1774. if (req.reportProgress) {
  1775. xhr.removeEventListener('progress', onDownProgress);
  1776. if (reqBody !== null && xhr.upload) {
  1777. xhr.upload.removeEventListener('progress', onUpProgress);
  1778. }
  1779. }
  1780. // Finally, abort the in-flight request.
  1781. xhr.abort();
  1782. };
  1783. });
  1784. };
  1785. HttpXhrBackend = __decorate([
  1786. core.Injectable(),
  1787. __metadata("design:paramtypes", [XhrFactory])
  1788. ], HttpXhrBackend);
  1789. return HttpXhrBackend;
  1790. }());
  1791. /**
  1792. * @license
  1793. * Copyright Google Inc. All Rights Reserved.
  1794. *
  1795. * Use of this source code is governed by an MIT-style license that can be
  1796. * found in the LICENSE file at https://angular.io/license
  1797. */
  1798. var XSRF_COOKIE_NAME = new core.InjectionToken('XSRF_COOKIE_NAME');
  1799. var XSRF_HEADER_NAME = new core.InjectionToken('XSRF_HEADER_NAME');
  1800. /**
  1801. * Retrieves the current XSRF token to use with the next outgoing request.
  1802. *
  1803. * @publicApi
  1804. */
  1805. var HttpXsrfTokenExtractor = /** @class */ (function () {
  1806. function HttpXsrfTokenExtractor() {
  1807. }
  1808. return HttpXsrfTokenExtractor;
  1809. }());
  1810. /**
  1811. * `HttpXsrfTokenExtractor` which retrieves the token from a cookie.
  1812. */
  1813. var HttpXsrfCookieExtractor = /** @class */ (function () {
  1814. function HttpXsrfCookieExtractor(doc, platform, cookieName) {
  1815. this.doc = doc;
  1816. this.platform = platform;
  1817. this.cookieName = cookieName;
  1818. this.lastCookieString = '';
  1819. this.lastToken = null;
  1820. /**
  1821. * @internal for testing
  1822. */
  1823. this.parseCount = 0;
  1824. }
  1825. HttpXsrfCookieExtractor.prototype.getToken = function () {
  1826. if (this.platform === 'server') {
  1827. return null;
  1828. }
  1829. var cookieString = this.doc.cookie || '';
  1830. if (cookieString !== this.lastCookieString) {
  1831. this.parseCount++;
  1832. this.lastToken = common.ɵparseCookieValue(cookieString, this.cookieName);
  1833. this.lastCookieString = cookieString;
  1834. }
  1835. return this.lastToken;
  1836. };
  1837. HttpXsrfCookieExtractor = __decorate([
  1838. core.Injectable(),
  1839. __param(0, core.Inject(common.DOCUMENT)), __param(1, core.Inject(core.PLATFORM_ID)),
  1840. __param(2, core.Inject(XSRF_COOKIE_NAME)),
  1841. __metadata("design:paramtypes", [Object, String, String])
  1842. ], HttpXsrfCookieExtractor);
  1843. return HttpXsrfCookieExtractor;
  1844. }());
  1845. /**
  1846. * `HttpInterceptor` which adds an XSRF token to eligible outgoing requests.
  1847. */
  1848. var HttpXsrfInterceptor = /** @class */ (function () {
  1849. function HttpXsrfInterceptor(tokenService, headerName) {
  1850. this.tokenService = tokenService;
  1851. this.headerName = headerName;
  1852. }
  1853. HttpXsrfInterceptor.prototype.intercept = function (req, next) {
  1854. var lcUrl = req.url.toLowerCase();
  1855. // Skip both non-mutating requests and absolute URLs.
  1856. // Non-mutating requests don't require a token, and absolute URLs require special handling
  1857. // anyway as the cookie set
  1858. // on our origin is not the same as the token expected by another origin.
  1859. if (req.method === 'GET' || req.method === 'HEAD' || lcUrl.startsWith('http://') ||
  1860. lcUrl.startsWith('https://')) {
  1861. return next.handle(req);
  1862. }
  1863. var token = this.tokenService.getToken();
  1864. // Be careful not to overwrite an existing header of the same name.
  1865. if (token !== null && !req.headers.has(this.headerName)) {
  1866. req = req.clone({ headers: req.headers.set(this.headerName, token) });
  1867. }
  1868. return next.handle(req);
  1869. };
  1870. HttpXsrfInterceptor = __decorate([
  1871. core.Injectable(),
  1872. __param(1, core.Inject(XSRF_HEADER_NAME)),
  1873. __metadata("design:paramtypes", [HttpXsrfTokenExtractor, String])
  1874. ], HttpXsrfInterceptor);
  1875. return HttpXsrfInterceptor;
  1876. }());
  1877. /**
  1878. * @license
  1879. * Copyright Google Inc. All Rights Reserved.
  1880. *
  1881. * Use of this source code is governed by an MIT-style license that can be
  1882. * found in the LICENSE file at https://angular.io/license
  1883. */
  1884. /**
  1885. * An injectable `HttpHandler` that applies multiple interceptors
  1886. * to a request before passing it to the given `HttpBackend`.
  1887. *
  1888. * The interceptors are loaded lazily from the injector, to allow
  1889. * interceptors to themselves inject classes depending indirectly
  1890. * on `HttpInterceptingHandler` itself.
  1891. * @see `HttpInterceptor`
  1892. */
  1893. var HttpInterceptingHandler = /** @class */ (function () {
  1894. function HttpInterceptingHandler(backend, injector) {
  1895. this.backend = backend;
  1896. this.injector = injector;
  1897. this.chain = null;
  1898. }
  1899. HttpInterceptingHandler.prototype.handle = function (req) {
  1900. if (this.chain === null) {
  1901. var interceptors = this.injector.get(HTTP_INTERCEPTORS, []);
  1902. this.chain = interceptors.reduceRight(function (next, interceptor) { return new HttpInterceptorHandler(next, interceptor); }, this.backend);
  1903. }
  1904. return this.chain.handle(req);
  1905. };
  1906. HttpInterceptingHandler = __decorate([
  1907. core.Injectable(),
  1908. __metadata("design:paramtypes", [HttpBackend, core.Injector])
  1909. ], HttpInterceptingHandler);
  1910. return HttpInterceptingHandler;
  1911. }());
  1912. /**
  1913. * Factory function that determines where to store JSONP callbacks.
  1914. *
  1915. * Ordinarily JSONP callbacks are stored on the `window` object, but this may not exist
  1916. * in test environments. In that case, callbacks are stored on an anonymous object instead.
  1917. *
  1918. *
  1919. */
  1920. function jsonpCallbackContext() {
  1921. if (typeof window === 'object') {
  1922. return window;
  1923. }
  1924. return {};
  1925. }
  1926. /**
  1927. * Configures XSRF protection support for outgoing requests.
  1928. *
  1929. * For a server that supports a cookie-based XSRF protection system,
  1930. * use directly to configure XSRF protection with the correct
  1931. * cookie and header names.
  1932. *
  1933. * If no names are supplied, the default cookie name is `XSRF-TOKEN`
  1934. * and the default header name is `X-XSRF-TOKEN`.
  1935. *
  1936. * @publicApi
  1937. */
  1938. var HttpClientXsrfModule = /** @class */ (function () {
  1939. function HttpClientXsrfModule() {
  1940. }
  1941. HttpClientXsrfModule_1 = HttpClientXsrfModule;
  1942. /**
  1943. * Disable the default XSRF protection.
  1944. */
  1945. HttpClientXsrfModule.disable = function () {
  1946. return {
  1947. ngModule: HttpClientXsrfModule_1,
  1948. providers: [
  1949. { provide: HttpXsrfInterceptor, useClass: NoopInterceptor },
  1950. ],
  1951. };
  1952. };
  1953. /**
  1954. * Configure XSRF protection.
  1955. * @param options An object that can specify either or both
  1956. * cookie name or header name.
  1957. * - Cookie name default is `XSRF-TOKEN`.
  1958. * - Header name default is `X-XSRF-TOKEN`.
  1959. *
  1960. */
  1961. HttpClientXsrfModule.withOptions = function (options) {
  1962. if (options === void 0) { options = {}; }
  1963. return {
  1964. ngModule: HttpClientXsrfModule_1,
  1965. providers: [
  1966. options.cookieName ? { provide: XSRF_COOKIE_NAME, useValue: options.cookieName } : [],
  1967. options.headerName ? { provide: XSRF_HEADER_NAME, useValue: options.headerName } : [],
  1968. ],
  1969. };
  1970. };
  1971. var HttpClientXsrfModule_1;
  1972. HttpClientXsrfModule = HttpClientXsrfModule_1 = __decorate([
  1973. core.NgModule({
  1974. providers: [
  1975. HttpXsrfInterceptor,
  1976. { provide: HTTP_INTERCEPTORS, useExisting: HttpXsrfInterceptor, multi: true },
  1977. { provide: HttpXsrfTokenExtractor, useClass: HttpXsrfCookieExtractor },
  1978. { provide: XSRF_COOKIE_NAME, useValue: 'XSRF-TOKEN' },
  1979. { provide: XSRF_HEADER_NAME, useValue: 'X-XSRF-TOKEN' },
  1980. ],
  1981. })
  1982. ], HttpClientXsrfModule);
  1983. return HttpClientXsrfModule;
  1984. }());
  1985. /**
  1986. * Configures the [dependency injector](guide/glossary#injector) for `HttpClient`
  1987. * with supporting services for XSRF. Automatically imported by `HttpClientModule`.
  1988. *
  1989. * You can add interceptors to the chain behind `HttpClient` by binding them to the
  1990. * multiprovider for built-in [DI token](guide/glossary#di-token) `HTTP_INTERCEPTORS`.
  1991. *
  1992. * @publicApi
  1993. */
  1994. var HttpClientModule = /** @class */ (function () {
  1995. function HttpClientModule() {
  1996. }
  1997. HttpClientModule = __decorate([
  1998. core.NgModule({
  1999. /**
  2000. * Optional configuration for XSRF protection.
  2001. */
  2002. imports: [
  2003. HttpClientXsrfModule.withOptions({
  2004. cookieName: 'XSRF-TOKEN',
  2005. headerName: 'X-XSRF-TOKEN',
  2006. }),
  2007. ],
  2008. /**
  2009. * Configures the [dependency injector](guide/glossary#injector) where it is imported
  2010. * with supporting services for HTTP communications.
  2011. */
  2012. providers: [
  2013. HttpClient,
  2014. { provide: HttpHandler, useClass: HttpInterceptingHandler },
  2015. HttpXhrBackend,
  2016. { provide: HttpBackend, useExisting: HttpXhrBackend },
  2017. BrowserXhr,
  2018. { provide: XhrFactory, useExisting: BrowserXhr },
  2019. ],
  2020. })
  2021. ], HttpClientModule);
  2022. return HttpClientModule;
  2023. }());
  2024. /**
  2025. * Configures the [dependency injector](guide/glossary#injector) for `HttpClient`
  2026. * with supporting services for JSONP.
  2027. * Without this module, Jsonp requests reach the backend
  2028. * with method JSONP, where they are rejected.
  2029. *
  2030. * You can add interceptors to the chain behind `HttpClient` by binding them to the
  2031. * multiprovider for built-in [DI token](guide/glossary#di-token) `HTTP_INTERCEPTORS`.
  2032. *
  2033. * @publicApi
  2034. */
  2035. var HttpClientJsonpModule = /** @class */ (function () {
  2036. function HttpClientJsonpModule() {
  2037. }
  2038. HttpClientJsonpModule = __decorate([
  2039. core.NgModule({
  2040. providers: [
  2041. JsonpClientBackend,
  2042. { provide: JsonpCallbackContext, useFactory: jsonpCallbackContext },
  2043. { provide: HTTP_INTERCEPTORS, useClass: JsonpInterceptor, multi: true },
  2044. ],
  2045. })
  2046. ], HttpClientJsonpModule);
  2047. return HttpClientJsonpModule;
  2048. }());
  2049. /**
  2050. * @license
  2051. * Copyright Google Inc. All Rights Reserved.
  2052. *
  2053. * Use of this source code is governed by an MIT-style license that can be
  2054. * found in the LICENSE file at https://angular.io/license
  2055. */
  2056. /**
  2057. * @license
  2058. * Copyright Google Inc. All Rights Reserved.
  2059. *
  2060. * Use of this source code is governed by an MIT-style license that can be
  2061. * found in the LICENSE file at https://angular.io/license
  2062. */
  2063. /**
  2064. * Generated bundle index. Do not edit.
  2065. */
  2066. exports.ɵangular_packages_common_http_http_a = NoopInterceptor;
  2067. exports.ɵangular_packages_common_http_http_b = JsonpCallbackContext;
  2068. exports.ɵangular_packages_common_http_http_c = jsonpCallbackContext;
  2069. exports.ɵangular_packages_common_http_http_d = BrowserXhr;
  2070. exports.ɵangular_packages_common_http_http_g = HttpXsrfCookieExtractor;
  2071. exports.ɵangular_packages_common_http_http_h = HttpXsrfInterceptor;
  2072. exports.ɵangular_packages_common_http_http_e = XSRF_COOKIE_NAME;
  2073. exports.ɵangular_packages_common_http_http_f = XSRF_HEADER_NAME;
  2074. exports.HttpBackend = HttpBackend;
  2075. exports.HttpHandler = HttpHandler;
  2076. exports.HttpClient = HttpClient;
  2077. exports.HttpHeaders = HttpHeaders;
  2078. exports.HTTP_INTERCEPTORS = HTTP_INTERCEPTORS;
  2079. exports.JsonpClientBackend = JsonpClientBackend;
  2080. exports.JsonpInterceptor = JsonpInterceptor;
  2081. exports.HttpClientJsonpModule = HttpClientJsonpModule;
  2082. exports.HttpClientModule = HttpClientModule;
  2083. exports.HttpClientXsrfModule = HttpClientXsrfModule;
  2084. exports.ɵHttpInterceptingHandler = HttpInterceptingHandler;
  2085. exports.HttpParams = HttpParams;
  2086. exports.HttpUrlEncodingCodec = HttpUrlEncodingCodec;
  2087. exports.HttpRequest = HttpRequest;
  2088. exports.HttpErrorResponse = HttpErrorResponse;
  2089. exports.HttpHeaderResponse = HttpHeaderResponse;
  2090. exports.HttpResponse = HttpResponse;
  2091. exports.HttpResponseBase = HttpResponseBase;
  2092. exports.HttpXhrBackend = HttpXhrBackend;
  2093. exports.XhrFactory = XhrFactory;
  2094. exports.HttpXsrfTokenExtractor = HttpXsrfTokenExtractor;
  2095. Object.defineProperty(exports, '__esModule', { value: true });
  2096. }));
  2097. //# sourceMappingURL=common-http.umd.js.map