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