UNPKG

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