http.js 82 KB

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