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