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