@angular/common 16.0.0-next.4 → 16.0.0-next.5

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