feat(common): new HttpClient API

HttpClient is an evolution of the existing Angular HTTP API, which exists
alongside of it in a separate package, @angular/common/http. This structure
ensures that existing codebases can slowly migrate to the new API.

The new API improves significantly on the ergonomics and features of the legacy
API. A partial list of new features includes:

* Typed, synchronous response body access, including support for JSON body types
* JSON is an assumed default and no longer needs to be explicitly parsed
* Interceptors allow middleware logic to be inserted into the pipeline
* Immutable request/response objects
* Progress events for both request upload and response download
* Post-request verification & flush based testing framework
This commit is contained in:
Alex Rickabaugh
2017-03-22 17:13:24 -07:00
committed by Jason Aden
parent 2a7ebbe982
commit 37797e2b4e
48 changed files with 5599 additions and 40 deletions

View File

@ -0,0 +1,25 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Observable} from 'rxjs/Observable';
import {HttpRequest} from './request';
import {HttpEvent} from './response';
/**
* @experimental
*/
export abstract class HttpHandler {
abstract handle(req: HttpRequest<any>): Observable<HttpEvent<any>>;
}
/**
* @experimental
*/
export abstract class HttpBackend implements HttpHandler {
abstract handle(req: HttpRequest<any>): Observable<HttpEvent<any>>;
}

View File

@ -0,0 +1,891 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {of } from 'rxjs/observable/of';
import {concatMap} from 'rxjs/operator/concatMap';
import {filter} from 'rxjs/operator/filter';
import {map} from 'rxjs/operator/map';
import {HttpHandler} from './backend';
import {HttpHeaders} from './headers';
import {HttpRequest} from './request';
import {HttpEvent, HttpEventType, HttpResponse} from './response';
/**
* Construct an instance of `HttpRequestOptions<T>` from a source `HttpMethodOptions` and
* the given `body`. Basically, this clones the object and adds the body.
*/
function addBody<T>(
options: {
headers?: HttpHeaders,
observe?: HttpObserve,
responseType?: 'arraybuffer' | 'blob' | 'json' | 'text',
withCredentials?: boolean,
},
body: T | null): any {
return {
body,
headers: options.headers,
observe: options.observe,
responseType: options.responseType,
withCredentials: options.withCredentials,
};
}
/**
* @experimental
*/
export type HttpObserve = 'body' | 'events' | 'response';
/**
* The main API for making outgoing HTTP requests.
*
* @experimental
*/
@Injectable()
export class HttpClient {
constructor(private handler: HttpHandler) {}
request<R>(req: HttpRequest<any>): Observable<HttpEvent<R>>;
request(method: string, url: string, options: {
body?: any,
headers?: HttpHeaders,
observe?: 'body',
responseType: 'arraybuffer', withCredentials?: boolean,
}): Observable<ArrayBuffer>;
request(method: string, url: string, options: {
body?: any,
headers?: HttpHeaders,
observe?: 'body',
responseType: 'blob', withCredentials?: boolean,
}): Observable<Blob>;
request(method: string, url: string, options: {
body?: any,
headers?: HttpHeaders,
observe?: 'body',
responseType: 'text', withCredentials?: boolean,
}): Observable<string>;
request(method: string, url: string, options: {
body?: any,
headers?: HttpHeaders,
observe: 'events',
responseType: 'arraybuffer', withCredentials?: boolean,
}): Observable<HttpEvent<ArrayBuffer>>;
request(method: string, url: string, options: {
body?: any,
headers?: HttpHeaders,
observe: 'events',
responseType: 'blob', withCredentials?: boolean,
}): Observable<HttpEvent<Blob>>;
request(method: string, url: string, options: {
body?: any,
headers?: HttpHeaders,
observe: 'events',
responseType: 'text', withCredentials?: boolean,
}): Observable<HttpEvent<string>>;
request<R>(method: string, url: string, options: {
body?: any,
headers?: HttpHeaders,
observe: 'events', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpEvent<R>>;
request(method: string, url: string, options: {
body?: any,
headers?: HttpHeaders,
observe: 'response',
responseType: 'arraybuffer', withCredentials?: boolean,
}): Observable<HttpResponse<ArrayBuffer>>;
request(method: string, url: string, options: {
body?: any,
headers?: HttpHeaders,
observe: 'response',
responseType: 'blob', withCredentials?: boolean,
}): Observable<HttpResponse<Blob>>;
request(method: string, url: string, options: {
body?: any,
headers?: HttpHeaders,
observe: 'response',
responseType: 'text', withCredentials?: boolean,
}): Observable<HttpResponse<string>>;
request<R>(method: string, url: string, options: {
body?: any,
headers?: HttpHeaders,
observe: 'response', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpResponse<R>>;
request(method: string, url: string, options?: {
body?: any,
headers?: HttpHeaders,
observe?: 'body',
responseType?: 'json',
withCredentials?: boolean,
}): Observable<Object>;
request<R>(method: string, url: string, options?: {
body?: any,
headers?: HttpHeaders,
observe?: 'body',
responseType?: 'json',
withCredentials?: boolean,
}): Observable<R>;
request(method: string, url: string, options?: {
body?: any,
headers?: HttpHeaders,
observe?: HttpObserve,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
}): Observable<any>;
/**
* Constructs an `Observable` for a particular HTTP request that, when subscribed,
* fires the request through the chain of registered interceptors and on to the
* server.
*
* This method can be called in one of two ways. Either an `HttpRequest`
* instance can be passed directly as the only parameter, or a method can be
* passed as the first parameter, a string URL as the second, and an
* options hash as the third.
*
* If a `HttpRequest` object is passed directly, an `Observable` of the
* raw `HttpEvent` stream will be returned.
*
* If a request is instead built by providing a URL, the options object
* determines the return type of `request()`. In addition to configuring
* request parameters such as the outgoing headers and/or the body, the options
* hash specifies two key pieces of information about the request: the
* `responseType` and what to `observe`.
*
* The `responseType` value determines how a successful response body will be
* parsed. If `responseType` is the default `json`, a type interface for the
* resulting object may be passed as a type parameter to `request()`.
*
* The `observe` value determines the return type of `request()`, based on what
* the consumer is interested in observing. A value of `events` will return an
* `Observable<HttpEvent>` representing the raw `HttpEvent` stream,
* including progress events by default. A value of `response` will return an
* `Observable<HttpResponse<T>>` where the `T` parameter of `HttpResponse`
* depends on the `responseType` and any optionally provided type parameter.
* A value of `body` will return an `Observable<T>` with the same `T` body type.
*/
request(first: string|HttpRequest<any>, url?: string, options: {
body?: any,
headers?: HttpHeaders,
observe?: HttpObserve,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
} = {}): Observable<any> {
let req: HttpRequest<any>;
// Firstly, check whether the primary argument is an instance of `HttpRequest`.
if (first instanceof HttpRequest) {
// It is. The other arguments must be undefined (per the signatures) and can be
// ignored.
req = first as HttpRequest<any>;
} else {
// It's a string, so it represents a URL. Construct a request based on it,
// and incorporate the remaining arguments (assuming GET unless a method is
// provided.
req = new HttpRequest(first, url !, options.body || null, {
headers: options.headers,
// By default, JSON is assumed to be returned for all calls.
responseType: options.responseType || 'json',
withCredentials: options.withCredentials,
});
}
// Start with an Observable.of() the initial request, and run the handler (which
// includes all interceptors) inside a concatMap(). This way, the handler runs
// inside an Observable chain, which causes interceptors to be re-run on every
// subscription (this also makes retries re-run the handler, including interceptors).
const events$: Observable<HttpEvent<any>> =
concatMap.call(of (req), (req: HttpRequest<any>) => this.handler.handle(req));
// If coming via the API signature which accepts a previously constructed HttpRequest,
// the only option is to get the event stream. Otherwise, return the event stream if
// that is what was requested.
if (first instanceof HttpRequest || options.observe === 'events') {
return events$;
}
// The requested stream contains either the full response or the body. In either
// case, the first step is to filter the event stream to extract a stream of
// responses(s).
const res$: Observable<HttpResponse<any>> =
filter.call(events$, (event: HttpEvent<any>) => event instanceof HttpResponse);
// Decide which stream to return.
switch (options.observe || 'body') {
case 'body':
// The requested stream is the body. Map the response stream to the response
// body. This could be done more simply, but a misbehaving interceptor might
// transform the response body into a different format and ignore the requested
// responseType. Guard against this by validating that the response is of the
// requested type.
switch (req.responseType) {
case 'arraybuffer':
return map.call(res$, (res: HttpResponse<any>) => {
// Validate that the body is an ArrayBuffer.
if (res.body !== null && !(res.body instanceof ArrayBuffer)) {
throw new Error('Response is not an ArrayBuffer.');
}
return res.body;
});
case 'blob':
return map.call(res$, (res: HttpResponse<any>) => {
// Validate that the body is a Blob.
if (res.body !== null && !(res.body instanceof Blob)) {
throw new Error('Response is not a Blob.');
}
return res.body;
});
case 'text':
return map.call(res$, (res: HttpResponse<any>) => {
// Validate that the body is a string.
if (res.body !== null && typeof res.body !== 'string') {
throw new Error('Response is not a string.');
}
return res.body;
});
case 'json':
default:
// No validation needed for JSON responses, as they can be of any type.
return map.call(res$, (res: HttpResponse<any>) => res.body);
}
case 'response':
// The response stream was requested directly, so return it.
return res$;
default:
// Guard against new future observe types being added.
throw new Error(`Unreachable: unhandled observe type ${options.observe}}`);
}
}
delete (url: string, options: {
headers?: HttpHeaders,
observe?: 'body',
responseType: 'arraybuffer', withCredentials?: boolean,
}): Observable<ArrayBuffer>;
delete (url: string, options: {
headers?: HttpHeaders,
observe?: 'body',
responseType: 'blob', withCredentials?: boolean,
}): Observable<Blob>;
delete (url: string, options: {
headers?: HttpHeaders,
observe?: 'body',
responseType: 'text', withCredentials?: boolean,
}): Observable<string>;
delete (url: string, options: {
headers?: HttpHeaders,
observe: 'events',
responseType: 'arraybuffer', withCredentials?: boolean,
}): Observable<HttpEvent<ArrayBuffer>>;
delete (url: string, options: {
headers?: HttpHeaders,
observe: 'events',
responseType: 'blob', withCredentials?: boolean,
}): Observable<HttpEvent<Blob>>;
delete (url: string, options: {
headers?: HttpHeaders,
observe: 'events',
responseType: 'text', withCredentials?: boolean,
}): Observable<HttpEvent<string>>;
delete (url: string, options: {
headers?: HttpHeaders,
observe: 'events', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpEvent<Object>>;
delete<T>(url: string, options: {
headers?: HttpHeaders,
observe: 'events', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpEvent<T>>;
delete (url: string, options: {
headers?: HttpHeaders,
observe: 'response',
responseType: 'arraybuffer', withCredentials?: boolean,
}): Observable<HttpResponse<ArrayBuffer>>;
delete (url: string, options: {
headers?: HttpHeaders,
observe: 'response',
responseType: 'blob', withCredentials?: boolean,
}): Observable<HttpResponse<Blob>>;
delete (url: string, options: {
headers?: HttpHeaders,
observe: 'response',
responseType: 'text', withCredentials?: boolean,
}): Observable<HttpResponse<string>>;
delete (url: string, options: {
headers?: HttpHeaders,
observe: 'response', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpResponse<Object>>;
delete<T>(url: string, options: {
headers?: HttpHeaders,
observe: 'response', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpResponse<T>>;
delete (url: string, options?: {
headers?: HttpHeaders,
observe?: 'body',
responseType?: 'json',
withCredentials?: boolean,
}): Observable<Object>;
delete<T>(url: string, options?: {
headers?: HttpHeaders,
observe?: 'body',
responseType?: 'json',
withCredentials?: boolean,
}): Observable<T>;
/**
* Constructs an `Observable` which, when subscribed, will cause the configured
* DELETE request to be executed on the server. See {@link HttpClient#request} for
* details of `delete()`'s return type based on the provided options.
*/
delete (url: string, options: {
headers?: HttpHeaders,
observe?: HttpObserve,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
} = {}): Observable<any> {
return this.request<any>('DELETE', url, options as any);
}
get(url: string, options: {
headers?: HttpHeaders,
observe?: 'body',
responseType: 'arraybuffer', withCredentials?: boolean,
}): Observable<ArrayBuffer>;
get(url: string, options: {
headers?: HttpHeaders,
observe?: 'body',
responseType: 'blob', withCredentials?: boolean,
}): Observable<Blob>;
get(url: string, options: {
headers?: HttpHeaders,
observe?: 'body',
responseType: 'text', withCredentials?: boolean,
}): Observable<string>;
get(url: string, options: {
headers?: HttpHeaders,
observe: 'events',
responseType: 'arraybuffer', withCredentials?: boolean,
}): Observable<HttpEvent<ArrayBuffer>>;
get(url: string, options: {
headers?: HttpHeaders,
observe: 'events',
responseType: 'blob', withCredentials?: boolean,
}): Observable<HttpEvent<Blob>>;
get(url: string, options: {
headers?: HttpHeaders,
observe: 'events',
responseType: 'text', withCredentials?: boolean,
}): Observable<HttpEvent<string>>;
get(url: string, options: {
headers?: HttpHeaders,
observe: 'events', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpEvent<Object>>;
get<T>(url: string, options: {
headers?: HttpHeaders,
observe: 'events', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpEvent<T>>;
get(url: string, options: {
headers?: HttpHeaders,
observe: 'response',
responseType: 'arraybuffer', withCredentials?: boolean,
}): Observable<HttpResponse<ArrayBuffer>>;
get(url: string, options: {
headers?: HttpHeaders,
observe: 'response',
responseType: 'blob', withCredentials?: boolean,
}): Observable<HttpResponse<Blob>>;
get(url: string, options: {
headers?: HttpHeaders,
observe: 'response',
responseType: 'text', withCredentials?: boolean,
}): Observable<HttpResponse<string>>;
get(url: string, options: {
headers?: HttpHeaders,
observe: 'response', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpResponse<Object>>;
get<T>(url: string, options: {
headers?: HttpHeaders,
observe: 'response', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpResponse<T>>;
get(url: string, options?: {
headers?: HttpHeaders,
observe?: 'body',
responseType?: 'json',
withCredentials?: boolean,
}): Observable<Object>;
get<T>(url: string, options?: {
headers?: HttpHeaders,
observe?: 'body',
responseType?: 'json',
withCredentials?: boolean,
}): Observable<T>;
/**
* Constructs an `Observable` which, when subscribed, will cause the configured
* GET request to be executed on the server. See {@link HttpClient#request} for
* details of `get()`'s return type based on the provided options.
*/
get(url: string, options: {
headers?: HttpHeaders,
observe?: HttpObserve,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
} = {}): Observable<any> {
return this.request<any>('GET', url, options as any);
}
head(url: string, options: {
headers?: HttpHeaders,
observe?: 'body',
responseType: 'arraybuffer', withCredentials?: boolean,
}): Observable<ArrayBuffer>;
head(url: string, options: {
headers?: HttpHeaders,
observe?: 'body',
responseType: 'blob', withCredentials?: boolean,
}): Observable<Blob>;
head(url: string, options: {
headers?: HttpHeaders,
observe?: 'body',
responseType: 'text', withCredentials?: boolean,
}): Observable<string>;
head(url: string, options: {
headers?: HttpHeaders,
observe: 'events',
responseType: 'arraybuffer', withCredentials?: boolean,
}): Observable<HttpEvent<ArrayBuffer>>;
head(url: string, options: {
headers?: HttpHeaders,
observe: 'events',
responseType: 'blob', withCredentials?: boolean,
}): Observable<HttpEvent<Blob>>;
head(url: string, options: {
headers?: HttpHeaders,
observe: 'events',
responseType: 'text', withCredentials?: boolean,
}): Observable<HttpEvent<string>>;
head(url: string, options: {
headers?: HttpHeaders,
observe: 'events', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpEvent<Object>>;
head<T>(url: string, options: {
headers?: HttpHeaders,
observe: 'events', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpEvent<T>>;
head(url: string, options: {
headers?: HttpHeaders,
observe: 'response',
responseType: 'arraybuffer', withCredentials?: boolean,
}): Observable<HttpResponse<ArrayBuffer>>;
head(url: string, options: {
headers?: HttpHeaders,
observe: 'response',
responseType: 'blob', withCredentials?: boolean,
}): Observable<HttpResponse<Blob>>;
head(url: string, options: {
headers?: HttpHeaders,
observe: 'response',
responseType: 'text', withCredentials?: boolean,
}): Observable<HttpResponse<string>>;
head(url: string, options: {
headers?: HttpHeaders,
observe: 'response', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpResponse<Object>>;
head<T>(url: string, options: {
headers?: HttpHeaders,
observe: 'response', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpResponse<T>>;
head(url: string, options?: {
headers?: HttpHeaders,
observe?: 'body',
responseType?: 'json',
withCredentials?: boolean,
}): Observable<Object>;
head<T>(url: string, options?: {
headers?: HttpHeaders,
observe?: 'body',
responseType?: 'json',
withCredentials?: boolean,
}): Observable<T>;
/**
* Constructs an `Observable` which, when subscribed, will cause the configured
* HEAD request to be executed on the server. See {@link HttpClient#request} for
* details of `head()`'s return type based on the provided options.
*/
head(url: string, options: {
headers?: HttpHeaders,
observe?: HttpObserve,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
} = {}): Observable<any> {
return this.request<any>('HEAD', url, options as any);
}
jsonp(url: string): Observable<any>;
jsonp<T>(url: string): Observable<T>;
/**
* Constructs an `Observable` which, when subscribed, will cause a request
* with the special method `JSONP` to be dispatched via the interceptor pipeline.
*
* A suitable interceptor must be installed (e.g. via the `HttpClientJsonpModule`).
* If no such interceptor is reached, then the `JSONP` request will likely be
* rejected by the configured backend.
*/
jsonp<T>(url: string): Observable<T> {
return this.request<any>('JSONP', url, {
observe: 'body',
responseType: 'json',
});
}
options(url: string, options: {
headers?: HttpHeaders,
observe?: 'body',
responseType: 'arraybuffer', withCredentials?: boolean,
}): Observable<ArrayBuffer>;
options(url: string, options: {
headers?: HttpHeaders,
observe?: 'body',
responseType: 'blob', withCredentials?: boolean,
}): Observable<Blob>;
options(url: string, options: {
headers?: HttpHeaders,
observe?: 'body',
responseType: 'text', withCredentials?: boolean,
}): Observable<string>;
options(url: string, options: {
headers?: HttpHeaders,
observe: 'events',
responseType: 'arraybuffer', withCredentials?: boolean,
}): Observable<HttpEvent<ArrayBuffer>>;
options(url: string, options: {
headers?: HttpHeaders,
observe: 'events',
responseType: 'blob', withCredentials?: boolean,
}): Observable<HttpEvent<Blob>>;
options(url: string, options: {
headers?: HttpHeaders,
observe: 'events',
responseType: 'text', withCredentials?: boolean,
}): Observable<HttpEvent<string>>;
options(url: string, options: {
headers?: HttpHeaders,
observe: 'events', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpEvent<Object>>;
options<T>(url: string, options: {
headers?: HttpHeaders,
observe: 'events', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpEvent<T>>;
options(url: string, options: {
headers?: HttpHeaders,
observe: 'response',
responseType: 'arraybuffer', withCredentials?: boolean,
}): Observable<HttpResponse<ArrayBuffer>>;
options(url: string, options: {
headers?: HttpHeaders,
observe: 'response',
responseType: 'blob', withCredentials?: boolean,
}): Observable<HttpResponse<Blob>>;
options(url: string, options: {
headers?: HttpHeaders,
observe: 'response',
responseType: 'text', withCredentials?: boolean,
}): Observable<HttpResponse<string>>;
options(url: string, options: {
headers?: HttpHeaders,
observe: 'response', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpResponse<Object>>;
options<T>(url: string, options: {
headers?: HttpHeaders,
observe: 'response', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpResponse<T>>;
options(url: string, options?: {
headers?: HttpHeaders,
observe?: 'body',
responseType?: 'json',
withCredentials?: boolean,
}): Observable<Object>;
options<T>(url: string, options?: {
headers?: HttpHeaders,
observe?: 'body',
responseType?: 'json',
withCredentials?: boolean,
}): Observable<T>;
/**
* Constructs an `Observable` which, when subscribed, will cause the configured
* OPTIONS request to be executed on the server. See {@link HttpClient#request} for
* details of `options()`'s return type based on the provided options.
*/
options(url: string, options: {
headers?: HttpHeaders,
observe?: HttpObserve,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
} = {}): Observable<any> {
return this.request<any>('OPTIONS', url, options as any);
}
patch(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe?: 'body',
responseType: 'arraybuffer', withCredentials?: boolean,
}): Observable<ArrayBuffer>;
patch(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe?: 'body',
responseType: 'blob', withCredentials?: boolean,
}): Observable<Blob>;
patch(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe?: 'body',
responseType: 'text', withCredentials?: boolean,
}): Observable<string>;
patch(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'events',
responseType: 'arraybuffer', withCredentials?: boolean,
}): Observable<HttpEvent<ArrayBuffer>>;
patch(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'events',
responseType: 'blob', withCredentials?: boolean,
}): Observable<HttpEvent<Blob>>;
patch(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'events',
responseType: 'text', withCredentials?: boolean,
}): Observable<HttpEvent<string>>;
patch(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'events', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpEvent<Object>>;
patch<T>(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'events', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpEvent<T>>;
patch(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'response',
responseType: 'arraybuffer', withCredentials?: boolean,
}): Observable<HttpResponse<ArrayBuffer>>;
patch(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'response',
responseType: 'blob', withCredentials?: boolean,
}): Observable<HttpResponse<Blob>>;
patch(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'response',
responseType: 'text', withCredentials?: boolean,
}): Observable<HttpResponse<string>>;
patch(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'response', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpResponse<Object>>;
patch<T>(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'response', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpResponse<T>>;
patch(url: string, body: any|null, options?: {
headers?: HttpHeaders,
observe?: 'body',
responseType?: 'json',
withCredentials?: boolean,
}): Observable<Object>;
patch<T>(url: string, body: any|null, options?: {
headers?: HttpHeaders,
observe?: 'body',
responseType?: 'json',
withCredentials?: boolean,
}): Observable<T>;
/**
* Constructs an `Observable` which, when subscribed, will cause the configured
* PATCH request to be executed on the server. See {@link HttpClient#request} for
* details of `patch()`'s return type based on the provided options.
*/
patch(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe?: HttpObserve,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
} = {}): Observable<any> {
return this.request<any>('PATCH', url, addBody(options, body));
}
post(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe?: 'body',
responseType: 'arraybuffer', withCredentials?: boolean,
}): Observable<ArrayBuffer>;
post(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe?: 'body',
responseType: 'blob', withCredentials?: boolean,
}): Observable<Blob>;
post(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe?: 'body',
responseType: 'text', withCredentials?: boolean,
}): Observable<string>;
post(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'events',
responseType: 'arraybuffer', withCredentials?: boolean,
}): Observable<HttpEvent<ArrayBuffer>>;
post(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'events',
responseType: 'blob', withCredentials?: boolean,
}): Observable<HttpEvent<Blob>>;
post(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'events',
responseType: 'text', withCredentials?: boolean,
}): Observable<HttpEvent<string>>;
post(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'events', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpEvent<Object>>;
post<T>(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'events', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpEvent<T>>;
post(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'response',
responseType: 'arraybuffer', withCredentials?: boolean,
}): Observable<HttpResponse<ArrayBuffer>>;
post(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'response',
responseType: 'blob', withCredentials?: boolean,
}): Observable<HttpResponse<Blob>>;
post(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'response',
responseType: 'text', withCredentials?: boolean,
}): Observable<HttpResponse<string>>;
post(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'response', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpResponse<Object>>;
post<T>(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'response', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpResponse<T>>;
post(url: string, body: any|null, options?: {
headers?: HttpHeaders,
observe?: 'body',
responseType?: 'json',
withCredentials?: boolean,
}): Observable<Object>;
post<T>(url: string, body: any|null, options?: {
headers?: HttpHeaders,
observe?: 'body',
responseType?: 'json',
withCredentials?: boolean,
}): Observable<T>;
/**
* Constructs an `Observable` which, when subscribed, will cause the configured
* POST request to be executed on the server. See {@link HttpClient#request} for
* details of `post()`'s return type based on the provided options.
*/
post(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe?: HttpObserve,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
} = {}): Observable<any> {
return this.request<any>('POST', url, addBody(options, body));
}
put(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe?: 'body',
responseType: 'arraybuffer', withCredentials?: boolean,
}): Observable<ArrayBuffer>;
put(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe?: 'body',
responseType: 'blob', withCredentials?: boolean,
}): Observable<Blob>;
put(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe?: 'body',
responseType: 'text', withCredentials?: boolean,
}): Observable<string>;
put(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'events',
responseType: 'arraybuffer', withCredentials?: boolean,
}): Observable<HttpEvent<ArrayBuffer>>;
put(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'events',
responseType: 'blob', withCredentials?: boolean,
}): Observable<HttpEvent<Blob>>;
put(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'events',
responseType: 'text', withCredentials?: boolean,
}): Observable<HttpEvent<string>>;
put(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'events', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpEvent<Object>>;
put<T>(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'events', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpEvent<T>>;
put(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'response',
responseType: 'arraybuffer', withCredentials?: boolean,
}): Observable<HttpResponse<ArrayBuffer>>;
put(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'response',
responseType: 'blob', withCredentials?: boolean,
}): Observable<HttpResponse<Blob>>;
put(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'response',
responseType: 'text', withCredentials?: boolean,
}): Observable<HttpResponse<string>>;
put(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'response', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpResponse<Object>>;
put<T>(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe: 'response', responseType?: 'json', withCredentials?: boolean,
}): Observable<HttpResponse<T>>;
put(url: string, body: any|null, options?: {
headers?: HttpHeaders,
observe?: 'body',
responseType?: 'json',
withCredentials?: boolean,
}): Observable<Object>;
put<T>(url: string, body: any|null, options?: {
headers?: HttpHeaders,
observe?: 'body',
responseType?: 'json',
withCredentials?: boolean,
}): Observable<T>;
/**
* Constructs an `Observable` which, when subscribed, will cause the configured
* POST request to be executed on the server. See {@link HttpClient#request} for
* details of `post()`'s return type based on the provided options.
*/
put(url: string, body: any|null, options: {
headers?: HttpHeaders,
observe?: HttpObserve,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
} = {}): Observable<any> {
return this.request<any>('PUT', url, addBody(options, body));
}
}

View File

@ -0,0 +1,214 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
interface Update {
name: string;
value?: string|string[];
op: 'a'|'s'|'d';
}
/**
* Immutable set of Http headers, with lazy parsing.
* @experimental
*/
export class HttpHeaders {
/**
* Internal map of lowercase header names to values.
*/
private headers: Map<string, string[]>;
/**
* Internal map of lowercased header names to the normalized
* form of the name (the form seen first).
*/
private normalizedNames: Map<string, string> = new Map();
/**
* Complete the lazy initialization of this object (needed before reading).
*/
private lazyInit: HttpHeaders|Function|null;
/**
* Queued updates to be materialized the next initialization.
*/
private lazyUpdate: Update[]|null = null;
constructor(headers?: string|{[name: string]: string | string[]}) {
if (!headers) {
this.headers = new Map<string, string[]>();
} else if (typeof headers === 'string') {
this.lazyInit = () => {
this.headers = new Map<string, string[]>();
headers.split('\n').forEach(line => {
const index = line.indexOf(':');
if (index > 0) {
const name = line.slice(0, index);
const key = name.toLowerCase();
const value = line.slice(index + 1).trim();
this.maybeSetNormalizedName(name, key);
if (this.headers.has(key)) {
this.headers.get(key) !.push(value);
} else {
this.headers.set(key, [value]);
}
}
});
};
} else {
this.lazyInit = () => {
this.headers = new Map<string, string[]>();
Object.keys(headers).forEach(name => {
let values: string|string[] = headers[name];
const key = name.toLowerCase();
if (typeof values === 'string') {
values = [values];
}
if (values.length > 0) {
this.headers.set(key, values);
this.maybeSetNormalizedName(name, key);
}
});
};
}
}
/**
* Checks for existence of header by given name.
*/
has(name: string): boolean {
this.init();
return this.headers.has(name.toLowerCase());
}
/**
* Returns first header that matches given name.
*/
get(name: string): string|null {
this.init();
const values = this.headers.get(name.toLowerCase());
return values && values.length > 0 ? values[0] : null;
}
/**
* Returns the names of the headers
*/
keys(): string[] {
this.init();
return Array.from(this.normalizedNames.values());
}
/**
* Returns list of header values for a given name.
*/
getAll(name: string): string[]|null {
this.init();
return this.headers.get(name.toLowerCase()) || null;
}
append(name: string, value: string|string[]): HttpHeaders {
return this.clone({name, value, op: 'a'});
}
set(name: string, value: string|string[]): HttpHeaders {
return this.clone({name, value, op: 's'});
}
delete (name: string, value?: string|string[]): HttpHeaders {
return this.clone({name, value, op: 'd'});
}
private maybeSetNormalizedName(name: string, lcName: string): void {
if (!this.normalizedNames.has(lcName)) {
this.normalizedNames.set(lcName, name);
}
}
private init(): void {
if (!!this.lazyInit) {
if (this.lazyInit instanceof HttpHeaders) {
this.copyFrom(this.lazyInit);
} else {
this.lazyInit();
}
this.lazyInit = null;
if (!!this.lazyUpdate) {
this.lazyUpdate.forEach(update => this.applyUpdate(update));
this.lazyUpdate = null;
}
}
}
private copyFrom(other: HttpHeaders) {
other.init();
Array.from(other.headers.keys()).forEach(key => {
this.headers.set(key, other.headers.get(key) !);
this.normalizedNames.set(key, other.normalizedNames.get(key) !);
});
}
private clone(update: Update): HttpHeaders {
const clone = new HttpHeaders();
clone.lazyInit =
(!!this.lazyInit && this.lazyInit instanceof HttpHeaders) ? this.lazyInit : this;
clone.lazyUpdate = (this.lazyUpdate || []).concat([update]);
return clone;
}
private applyUpdate(update: Update): void {
const key = update.name.toLowerCase();
switch (update.op) {
case 'a':
case 's':
let value = update.value !;
if (typeof value === 'string') {
value = [value];
}
if (value.length === 0) {
return;
}
this.maybeSetNormalizedName(update.name, key);
const base = (update.op === 'a' ? this.headers.get(key) : undefined) || [];
base.push(...value);
this.headers.set(key, base);
break;
case 'd':
const toDelete = update.value as string | undefined;
if (!toDelete) {
this.headers.delete(key);
this.normalizedNames.delete(key);
} else {
let existing = this.headers.get(key);
if (!existing) {
return;
}
existing = existing.filter(value => toDelete.indexOf(value) === -1);
if (existing.length === 0) {
this.headers.delete(key);
this.normalizedNames.delete(key);
} else {
this.headers.set(key, existing);
}
}
break;
}
}
/**
* @internal
*/
forEach(fn: (name: string, values: string[]) => void) {
this.init();
Array.from(this.normalizedNames.keys())
.forEach(key => fn(this.normalizedNames.get(key) !, this.headers.get(key) !));
}
}

View File

@ -0,0 +1,66 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {InjectionToken} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {HttpHandler} from './backend';
import {HttpRequest} from './request';
import {HttpEvent, HttpResponse} from './response';
/**
* Intercepts `HttpRequest` and handles them.
*
* Most interceptors will transform the outgoing request before passing it to the
* next interceptor in the chain, by calling `next.handle(transformedReq)`.
*
* In rare cases, interceptors may wish to completely handle a request themselves,
* and not delegate to the remainder of the chain. This behavior is allowed.
*
* @experimental
*/
export interface HttpInterceptor {
/**
* Intercept an outgoing `HttpRequest` and optionally transform it or the
* response.
*
* Typically an interceptor will transform the outgoing request before returning
* `next.handle(transformedReq)`. An interceptor may choose to transform the
* response event stream as well, by applying additional Rx operators on the stream
* returned by `next.handle()`.
*
* More rarely, an interceptor may choose to completely handle the request itself,
* and compose a new event stream instead of invoking `next.handle()`. This is
* acceptable behavior, but keep in mind further interceptors will be skipped entirely.
*
* It is also rare but valid for an interceptor to return multiple responses on the
* event stream for a single request.
*/
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>;
}
/**
* `HttpHandler` which applies an `HttpInterceptor` to an `HttpRequest`.
*
* @experimental
*/
export class HttpInterceptorHandler implements HttpHandler {
constructor(private next: HttpHandler, private interceptor: HttpInterceptor) {}
handle(req: HttpRequest<any>): Observable<HttpEvent<any>> {
return this.interceptor.intercept(req, this.next);
}
}
/**
* A multi-provider token which represents the array of `HttpInterceptor`s that
* are registered.
*
* @experimental
*/
export const HTTP_INTERCEPTORS = new InjectionToken<HttpInterceptor[]>('HTTP_INTERCEPTORS');

View File

@ -0,0 +1,224 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {DOCUMENT} from '@angular/common';
import {Inject, Injectable, InjectionToken} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Observer} from 'rxjs/Observer';
import {HttpBackend, HttpHandler} from './backend';
import {HttpInterceptor} from './interceptor';
import {HttpRequest} from './request';
import {HttpErrorResponse, HttpEvent, HttpEventType, HttpResponse} from './response';
// Every request made through JSONP needs a callback name that's unique across the
// whole page. Each request is assigned an id and the callback name is constructed
// from that. The next id to be assigned is tracked in a global variable here that
// is shared among all applications on the page.
let nextRequestId: number = 0;
// Error text given when a JSONP script is injected, but doesn't invoke the callback
// passed in its URL.
export const JSONP_ERR_NO_CALLBACK = 'JSONP injected script did not invoke callback.';
// Error text given when a request is passed to the JsonpClientBackend that doesn't
// have a request method JSONP.
export const JSONP_ERR_WRONG_METHOD = 'JSONP requests must use JSONP request method.';
export const JSONP_ERR_WRONG_RESPONSE_TYPE = 'JSONP requests must use Json response type.';
/**
* DI token/abstract type representing a map of JSONP callbacks.
*
* In the browser, this should always be the `window` object.
*
* @experimental
*/
export abstract class JsonpCallbackContext { [key: string]: (data: any) => void; }
/**
* `HttpBackend` that only processes `HttpRequest` with the JSONP method,
* by performing JSONP style requests.
*
* @experimental
*/
@Injectable()
export class JsonpClientBackend implements HttpBackend {
constructor(private callbackMap: JsonpCallbackContext, @Inject(DOCUMENT) private document: any) {}
/**
* Get the name of the next callback method, by incrementing the global `nextRequestId`.
*/
private nextCallback(): string { return `ng_jsonp_callback_${nextRequestId++}`; }
/**
* Process a JSONP request and return an event stream of the results.
*/
handle(req: HttpRequest<never>): Observable<HttpEvent<any>> {
// Firstly, check both the method and response type. If either doesn't match
// then the request was improperly routed here and cannot be handled.
if (req.method !== 'JSONP') {
throw new Error(JSONP_ERR_WRONG_METHOD);
} else if (req.responseType !== 'json') {
throw new Error(JSONP_ERR_WRONG_RESPONSE_TYPE);
}
// Everything else happens inside the Observable boundary.
return new Observable<HttpEvent<any>>((observer: Observer<HttpEvent<any>>) => {
// The first step to make a request is to generate the callback name, and replace the
// callback placeholder in the URL with the name. Care has to be taken here to ensure
// a trailing &, if matched, gets inserted back into the URL in the correct place.
const callback = this.nextCallback();
const url = req.url.replace(/=JSONP_CALLBACK(&|$)/, `=${callback}$1`);
// Construct the <script> tag and point it at the URL.
const node = this.document.createElement('script');
node.src = url;
// A JSONP request requires waiting for multiple callbacks. These variables
// are closed over and track state across those callbacks.
// The response object, if one has been received, or null otherwise.
let body: any|null = null;
// Whether the response callback has been called.
let finished: boolean = false;
// Whether the request has been cancelled (and thus any other callbacks)
// should be ignored.
let cancelled: boolean = false;
// Set the response callback in this.callbackMap (which will be the window
// object in the browser. The script being loaded via the <script> tag will
// eventually call this callback.
this.callbackMap[callback] = (data?: any) => {
// Data has been received from the JSONP script. Firstly, delete this callback.
delete this.callbackMap[callback];
// Next, make sure the request wasn't cancelled in the meantime.
if (cancelled) {
return;
}
// Set state to indicate data was received.
body = data;
finished = true;
};
// cleanup() is a utility closure that removes the <script> from the page and
// the response callback from the window. This logic is used in both the
// success, error, and cancellation paths, so it's extracted out for convenience.
const cleanup = () => {
// Remove the <script> tag if it's still on the page.
if (node.parentNode) {
node.parentNode.removeChild(node);
}
// Remove the response callback from the callbackMap (window object in the
// browser).
delete this.callbackMap[callback];
};
// onLoad() is the success callback which runs after the response callback
// if the JSONP script loads successfully. The event itself is unimportant.
// If something went wrong, onLoad() may run without the response callback
// having been invoked.
const onLoad = (event: Event) => {
// Do nothing if the request has been cancelled.
if (cancelled) {
return;
}
// Cleanup the page.
cleanup();
// Check whether the response callback has run.
if (!finished) {
// It hasn't, something went wrong with the request. Return an error via
// the Observable error path. All JSONP errors have status 0.
observer.error(new HttpErrorResponse({
url,
status: 0,
statusText: 'JSONP Error',
error: new Error(JSONP_ERR_NO_CALLBACK),
}));
return;
}
// Success. body either contains the response body or null if none was
// returned.
observer.next(new HttpResponse({
body,
status: 200,
statusText: 'OK', url,
}));
// Complete the stream, the resposne is over.
observer.complete();
};
// onError() is the error callback, which runs if the script returned generates
// a Javascript error. It emits the error via the Observable error channel as
// a HttpErrorResponse.
const onError: any = (error: Error) => {
// If the request was already cancelled, no need to emit anything.
if (cancelled) {
return;
}
cleanup();
// Wrap the error in a HttpErrorResponse.
observer.error(new HttpErrorResponse({
error,
status: 0,
statusText: 'JSONP Error', url,
}));
};
// Subscribe to both the success (load) and error events on the <script> tag,
// and add it to the page.
node.addEventListener('load', onLoad);
node.addEventListener('error', onError);
this.document.body.appendChild(node);
// The request has now been successfully sent.
observer.next({type: HttpEventType.Sent});
// Cancellation handler.
return () => {
// Track the cancellation so event listeners won't do anything even if already scheduled.
cancelled = true;
// Remove the event listeners so they won't run if the events later fire.
node.removeEventListener('load', onLoad);
node.removeEventListener('error', onError);
// And finally, clean up the page.
cleanup();
};
});
}
}
/**
* An `HttpInterceptor` which identifies requests with the method JSONP and
* shifts them to the `JsonpClientBackend`.
*
* @experimental
*/
@Injectable()
export class JsonpInterceptor {
constructor(private jsonp: JsonpClientBackend) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.method === 'JSONP') {
return this.jsonp.handle(req as HttpRequest<never>);
}
// Fall through for normal HTTP requests.
return next.handle(req);
}
}

View File

@ -0,0 +1,93 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Inject, NgModule, Optional} from '@angular/core';
import {HttpBackend, HttpHandler} from './backend';
import {HttpClient} from './client';
import {HTTP_INTERCEPTORS, HttpInterceptor, HttpInterceptorHandler} from './interceptor';
import {JsonpCallbackContext, JsonpClientBackend, JsonpInterceptor} from './jsonp';
import {BrowserXhr, HttpXhrBackend, XhrFactory} from './xhr';
/**
* Constructs an `HttpHandler` that applies a bunch of `HttpInterceptor`s
* to a request before passing it to the given `HttpBackend`.
*
* Meant to be used as a factory function within `HttpClientModule`.
*
* @experimental
*/
export function interceptingHandler(
backend: HttpBackend, interceptors: HttpInterceptor[] | null = []): HttpHandler {
if (!interceptors) {
return backend;
}
return interceptors.reduceRight(
(next, interceptor) => new HttpInterceptorHandler(next, interceptor), backend);
}
/**
* Factory function that determines where to store JSONP callbacks.
*
* Ordinarily JSONP callbacks are stored on the `window` object, but this may not exist
* in test environments. In that case, callbacks are stored on an anonymous object instead.
*
* @experimental
*/
export function jsonpCallbackContext(): Object {
if (typeof window === 'object') {
return window;
}
return {};
}
/**
* `NgModule` which provides the `HttpClient` and associated services.
*
* Interceptors can be added to the chain behind `HttpClient` by binding them
* to the multiprovider for `HTTP_INTERCEPTORS`.
*
* @experimental
*/
@NgModule({
providers: [
HttpClient,
// HttpHandler is the backend + interceptors and is constructed
// using the interceptingHandler factory function.
{
provide: HttpHandler,
useFactory: interceptingHandler,
deps: [HttpBackend, [new Optional(), new Inject(HTTP_INTERCEPTORS)]],
},
HttpXhrBackend,
{provide: HttpBackend, useExisting: HttpXhrBackend},
BrowserXhr,
{provide: XhrFactory, useExisting: BrowserXhr},
],
})
export class HttpClientModule {
}
/**
* `NgModule` which enables JSONP support in `HttpClient`.
*
* Without this module, Jsonp requests will reach the backend
* with method JSONP, where they'll be rejected.
*
* @experimental
*/
@NgModule({
providers: [
JsonpClientBackend,
{provide: JsonpCallbackContext, useFactory: jsonpCallbackContext},
{provide: HTTP_INTERCEPTORS, useClass: JsonpInterceptor, multi: true},
],
})
export class HttpClientJsonpModule {
}

View File

@ -0,0 +1,325 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {HttpHeaders} from './headers';
/**
* Construction interface for `HttpRequest`s.
*
* All values are optional and will override default values if provided.
*/
interface HttpRequestInit {
headers?: HttpHeaders, reportProgress?: boolean,
responseType?: 'arraybuffer'|'blob'|'json'|'text', withCredentials?: boolean,
}
/**
* Determine whether the given HTTP method may include a body.
*/
function mightHaveBody(method: string): boolean {
switch (method) {
case 'DELETE':
case 'GET':
case 'HEAD':
case 'OPTIONS':
case 'JSONP':
return false;
default:
return true;
}
}
/**
* Safely assert whether the given value is an ArrayBuffer.
*
* In some execution environments ArrayBuffer is not defined.
*/
function isArrayBuffer(value: any): value is ArrayBuffer {
return typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer;
}
/**
* Safely assert whether the given value is a Blob.
*
* In some execution environments Blob is not defined.
*/
function isBlob(value: any): value is Blob {
return typeof Blob !== 'undefined' && value instanceof Blob;
}
/**
* Safely assert whether the given value is a FormData instance.
*
* In some execution environments FormData is not defined.
*/
function isFormData(value: any): value is FormData {
return typeof FormData !== 'undefined' && value instanceof FormData;
}
function isUrlEncodedBody(value: any): value is Object {
return typeof value === 'object' && value['__HttpUrlEncodedBody'];
}
/**
* An outgoing HTTP request with an optional typed body.
*
* `HttpRequest` represents an outgoing request, including URL, method,
* headers, body, and other request configuration options. Instances should be
* assumed to be immutable. To modify a `HttpRequest`, the `clone`
* method should be used.
*
* @experimental
*/
export class HttpRequest<T> {
/**
* The request body, or `null` if one isn't set.
*
* Bodies are not enforced to be immutable, as they can include a reference to any
* user-defined data type. However, interceptors should take care to preserve
* idempotence by treating them as such.
*/
readonly body: T|null = null;
/**
* Outgoing headers for this request.
*/
readonly headers: HttpHeaders;
/**
* Whether this request should be made in a way that exposes progress events.
*
* Progress events are expensive (change detection runs on each event) and so
* they should only be requested if the consumer intends to monitor them.
*/
readonly reportProgress: boolean = false;
/**
* Whether this request should be sent with outgoing credentials (cookies).
*/
readonly withCredentials: boolean = false;
/**
* The expected response type of the server.
*
* This is used to parse the response appropriately before returning it to
* the requestee.
*/
readonly responseType: 'arraybuffer'|'blob'|'json'|'text' = 'json';
/**
* The outgoing HTTP request method.
*/
readonly method: string;
constructor(method: 'DELETE'|'GET'|'HEAD'|'JSONP'|'OPTIONS', url: string, init?: {
headers?: HttpHeaders,
reportProgress?: boolean,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
});
constructor(method: 'POST'|'PUT'|'PATCH', url: string, body: T|null, init?: {
headers?: HttpHeaders,
reportProgress?: boolean,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
});
constructor(method: string, url: string, body: T|null, init?: {
headers?: HttpHeaders,
reportProgress?: boolean,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
});
constructor(
method: string, public url: string, third?: T|{
headers?: HttpHeaders,
reportProgress?: boolean,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
}|null,
fourth?: {
headers?: HttpHeaders,
reportProgress?: boolean,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
}) {
this.method = method.toUpperCase();
// Next, need to figure out which argument holds the HttpRequestInit
// options, if any.
let options: HttpRequestInit|undefined;
// Check whether a body argument is expected. The only valid way to omit
// the body argument is to use a known no-body method like GET.
if (mightHaveBody(this.method) || !!fourth) {
// Body is the third argument, options are the fourth.
this.body = third as T || null;
options = fourth;
} else {
// No body required, options are the third argument. The body stays null.
options = third as HttpRequestInit;
}
// If options have been passed, interpret them.
if (options) {
// Normalize reportProgress and withCredentials.
this.reportProgress = !!options.reportProgress;
this.withCredentials = !!options.withCredentials;
// Override default response type of 'json' if one is provided.
if (!!options.responseType) {
this.responseType = options.responseType;
}
// Override headers if they're provided.
if (!!options.headers) {
this.headers = options.headers;
}
}
// If no headers have been passed in, construct a new HttpHeaders instance.
if (!this.headers) {
this.headers = new HttpHeaders();
}
}
/**
* Transform the free-form body into a serialized format suitable for
* transmission to the server.
*/
serializeBody(): ArrayBuffer|Blob|FormData|string|null {
// If no body is present, no need to serialize it.
if (this.body === null) {
return null;
}
// Check whether the body is already in a serialized form. If so,
// it can just be returned directly.
if (isArrayBuffer(this.body) || isBlob(this.body) || isFormData(this.body) ||
typeof this.body === 'string') {
return this.body;
}
// Check whether the body is an instance of HttpUrlEncodedBody, avoiding any direct
// references to the class in order to permit it being tree-shaken.
if (isUrlEncodedBody(this.body)) {
return this.body.toString();
}
// Check whether the body is an object or array, and serialize with JSON if so.
if (typeof this.body === 'object' || typeof this.body === 'boolean' ||
Array.isArray(this.body)) {
return JSON.stringify(this.body);
}
// Fall back on toString() for everything else.
return (this.body as any).toString();
}
/**
* Examine the body and attempt to infer an appropriate MIME type
* for it.
*
* If no such type can be inferred, this method will return `null`.
*/
detectContentTypeHeader(): string|null {
// An empty body has no content type.
if (this.body === null) {
return null;
}
// FormData instances are URL encoded on the wire.
if (isFormData(this.body)) {
return 'multipart/form-data';
}
// Blobs usually have their own content type. If it doesn't, then
// no type can be inferred.
if (isBlob(this.body)) {
return this.body.type || null;
}
// Array buffers have unknown contents and thus no type can be inferred.
if (isArrayBuffer(this.body)) {
return null;
}
// Technically, strings could be a form of JSON data, but it's safe enough
// to assume they're plain strings.
if (typeof this.body === 'string') {
return 'text/plain';
}
// `HttpUrlEncodedBody` is detected specially so as to allow it to be
// tree-shaken.
if (isUrlEncodedBody(this.body)) {
return 'application/x-www-form-urlencoded;charset=UTF-8';
}
// Arrays, objects, and numbers will be encoded as JSON.
if (typeof this.body === 'object' || typeof this.body === 'number' ||
Array.isArray(this.body)) {
return 'application/json';
}
// No type could be inferred.
return null;
}
clone(): HttpRequest<T>;
clone(update: {
headers?: HttpHeaders,
reportProgress?: boolean,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
}): HttpRequest<T>;
clone<V>(update: {
headers?: HttpHeaders,
reportProgress?: boolean,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
body?: V|null,
method?: string,
url?: string,
setHeaders?: {[name: string]: string | string[]},
}): HttpRequest<V>;
clone(update: {
headers?: HttpHeaders,
reportProgress?: boolean,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
body?: any|null,
method?: string,
url?: string,
setHeaders?: {[name: string]: string | string[]},
} = {}): HttpRequest<any> {
// For method, url, and responseType, take the current value unless
// it is overridden in the update hash.
const method = update.method || this.method;
const url = update.url || this.url;
const responseType = update.responseType || this.responseType;
// The body is somewhat special - a `null` value in update.body means
// whatever current body is present is being overridden with an empty
// body, whereas an `undefined` value in update.body implies no
// override.
const body = (update.body !== undefined) ? update.body : this.body;
// Carefully handle the boolean options to differentiate between
// `false` and `undefined` in the update args.
const withCredentials =
(update.withCredentials !== undefined) ? update.withCredentials : this.withCredentials;
const reportProgress =
(update.reportProgress !== undefined) ? update.reportProgress : this.reportProgress;
// Headers may need to be cloned later if they're sealed, but being
// appended to.
let headers = update.headers || this.headers;
// Check whether the caller has asked to add headers.
if (update.setHeaders !== undefined) {
// Set every requested header.
headers =
Object.keys(update.setHeaders)
.reduce((headers, name) => headers.set(name, update.setHeaders ![name]), headers);
}
// Finally, construct the new HttpRequest using the pieces from above.
return new HttpRequest(
method, url, body, {
headers, reportProgress, responseType, withCredentials,
});
}
}

View File

@ -0,0 +1,329 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Observable} from 'rxjs/Observable';
import {empty} from 'rxjs/observable/empty';
import {HttpHeaders} from './headers';
/**
* Type enumeration for the different kinds of `HttpEvent`.
*
* @experimental
*/
export enum HttpEventType {
/**
* The request was sent out over the wire.
*/
Sent,
/**
* An upload progress event was received.
*/
UploadProgress,
/**
* The response status code and headers were received.
*/
ResponseHeader,
/**
* A download progress event was received.
*/
DownloadProgress,
/**
* The full response including the body was received.
*/
Response,
/**
* A custom event from an interceptor or a backend.
*/
User,
}
/**
* Base interface for progress events.
*
* @experimental
*/
export interface HttpProgressEvent {
/**
* Progress event type is either upload or download.
*/
type: HttpEventType.DownloadProgress|HttpEventType.UploadProgress;
/**
* Number of bytes uploaded or downloaded.
*/
loaded: number;
/**
* Total number of bytes to upload or download. Depending on the request or
* response, this may not be computable and thus may not be present.
*/
total?: number;
}
/**
* A download progress event.
*
* @experimental
*/
export interface HttpDownloadProgressEvent extends HttpProgressEvent {
type: HttpEventType.DownloadProgress;
/**
* The partial response body as downloaded so far.
*
* Only present if the responseType was `text`.
*/
partialText?: string;
}
/**
* An upload progress event.
*
* @experimental
*/
export interface HttpUploadProgressEvent extends HttpProgressEvent {
type: HttpEventType.UploadProgress;
}
/**
* An event indicating that the request was sent to the server. Useful
* when a request may be retried multiple times, to distinguish between
* retries on the final event stream.
*
* @experimental
*/
export interface HttpSentEvent { type: HttpEventType.Sent; }
/**
* A user-defined event.
*
* Grouping all custom events under this type ensures they will be handled
* and forwarded by all implementations of interceptors.
*
* @experimental
*/
export interface HttpUserEvent<T> { type: HttpEventType.User; }
/**
* An error that represents a failed attempt to JSON.parse text coming back
* from the server.
*
* It bundles the Error object with the actual response body that failed to parse.
*
* @experimental
*/
export interface HttpJsonParseError { error: Error, text: string, }
/**
* Union type for all possible events on the response stream.
*
* Typed according to the expected type of the response.
*
* @experimental
*/
export type HttpEvent<T> =
HttpSentEvent | HttpHeaderResponse | HttpResponse<T>| HttpProgressEvent | HttpUserEvent<T>;
/**
* Base class for both `HttpResponse` and `HttpHeaderResponse`.
*
* @experimental
*/
export abstract class HttpResponseBase {
/**
* All response headers.
*/
readonly headers: HttpHeaders;
/**
* Response status code.
*/
readonly status: number;
/**
* Textual description of response status code.
*
* Do not depend on this.
*/
readonly statusText: string;
/**
* URL of the resource retrieved, or null if not available.
*/
readonly url: string|null;
/**
* Whether the status code falls in the 2xx range.
*/
readonly ok: boolean;
/**
* Type of the response, narrowed to either the full response or the header.
*/
readonly type: HttpEventType.Response|HttpEventType.ResponseHeader;
/**
* Super-constructor for all responses.
*
* The single parameter accepted is an initialization hash. Any properties
* of the response passed there will override the default values.
*/
constructor(
init: {
headers?: HttpHeaders,
status?: number,
statusText?: string,
url?: string,
},
defaultStatus: number = 200, defaultStatusText: string = 'OK') {
// If the hash has values passed, use them to initialize the response.
// Otherwise use the default values.
this.headers = init.headers || new HttpHeaders();
this.status = init.status !== undefined ? init.status : defaultStatus;
this.statusText = init.statusText || defaultStatusText;
this.url = init.url || null;
// Cache the ok value to avoid defining a getter.
this.ok = this.status >= 200 && this.status < 300;
}
}
/**
* A partial HTTP response which only includes the status and header data,
* but no response body.
*
* `HttpHeaderResponse` is a `HttpEvent` available on the response
* event stream, only when progress events are requested.
*
* @experimental
*/
export class HttpHeaderResponse extends HttpResponseBase {
/**
* Create a new `HttpHeaderResponse` with the given parameters.
*/
constructor(init: {
headers?: HttpHeaders,
status?: number,
statusText?: string,
url?: string,
} = {}) {
super(init);
}
readonly type: HttpEventType.ResponseHeader = HttpEventType.ResponseHeader;
/**
* Copy this `HttpHeaderResponse`, overriding its contents with the
* given parameter hash.
*/
clone(update: {headers?: HttpHeaders; status?: number; statusText?: string; url?: string;} = {}):
HttpHeaderResponse {
// Perform a straightforward initialization of the new HttpHeaderResponse,
// overriding the current parameters with new ones if given.
return new HttpHeaderResponse({
headers: update.headers || this.headers,
status: update.status !== undefined ? update.status : this.status,
statusText: update.statusText || this.statusText,
url: update.url || this.url || undefined,
})
}
}
/**
* A full HTTP response, including a typed response body (which may be `null`
* if one was not returned).
*
* `HttpResponse` is a `HttpEvent` available on the response event
* stream.
*
* @experimental
*/
export class HttpResponse<T> extends HttpResponseBase {
/**
* The response body, or `null` if one was not returned.
*/
readonly body: T|null;
/**
* Construct a new `HttpResponse`.
*/
constructor(init: {
body?: T | null, headers?: HttpHeaders; status?: number; statusText?: string; url?: string;
} = {}) {
super(init);
this.body = init.body || null;
}
readonly type: HttpEventType.Response = HttpEventType.Response;
clone(): HttpResponse<T>;
clone(update: {headers?: HttpHeaders; status?: number; statusText?: string; url?: string;}):
HttpResponse<T>;
clone<V>(update: {
body?: V | null, headers?: HttpHeaders; status?: number; statusText?: string; url?: string;
}): HttpResponse<V>;
clone(update: {
body?: any | null; headers?: HttpHeaders; status?: number; statusText?: string; url?: string;
} = {}): HttpResponse<any> {
return new HttpResponse<any>({
body: (update.body !== undefined) ? update.body : this.body,
headers: update.headers || this.headers,
status: (update.status !== undefined) ? update.status : this.status,
statusText: update.statusText || this.statusText,
url: update.url || this.url || undefined,
});
}
}
/**
* A response that represents an error or failure, either from a
* non-successful HTTP status, an error while executing the request,
* or some other failure which occurred during the parsing of the response.
*
* Any error returned on the `Observable` response stream will be
* wrapped in an `HttpErrorResponse` to provide additional context about
* the state of the HTTP layer when the error occurred. The error property
* will contain either a wrapped Error object or the error response returned
* from the server.
*
* @experimental
*/
export class HttpErrorResponse extends HttpResponseBase implements Error {
readonly name = 'HttpErrorResponse';
readonly message: string;
readonly error: any|null;
/**
* Errors are never okay, even when the status code is in the 2xx success range.
*/
readonly ok = false;
constructor(init: {
error?: any; headers?: HttpHeaders; status?: number; statusText?: string; url?: string;
}) {
// Initialize with a default status of 0 / Unknown Error.
super(init, 0, 'Unknown Error');
// If the response was successful, then this was a parse error. Otherwise, it was
// a protocol-level failure of some sort. Either the request failed in transit
// or the server returned an unsuccessful status code.
if (this.status >= 200 && this.status < 300) {
this.message = `Http failure during parsing for ${init.url || '(unknown url)'}`;
} else {
this.message =
`Http failure response for ${init.url || '(unknown url)'}: ${init.status} ${init.statusText}`;
}
this.error = init.error || null;
}
}

View File

@ -0,0 +1,214 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* A codec for encoding and decoding parameters in URLs.
*
* Used by `HttpUrlEncodedBody`.
*
* @experimental
**/
export interface HttpUrlParameterCodec {
encodeKey(key: string): string;
encodeValue(value: string): string;
decodeKey(key: string): string;
decodeValue(value: string): string;
}
/**
* A `HttpUrlParameterCodec` that uses `encodeURIComponent` and `decodeURIComponent` to
* serialize and parse URL parameter keys and values.
*
* @experimental
*/
export class HttpStandardUrlParameterCodec implements HttpUrlParameterCodec {
encodeKey(k: string): string { return standardEncoding(k); }
encodeValue(v: string): string { return standardEncoding(v); }
decodeKey(k: string): string { return decodeURIComponent(k); }
decodeValue(v: string) { return decodeURIComponent(v); }
}
function paramParser(rawParams: string, codec: HttpUrlParameterCodec): Map<string, string[]> {
const map = new Map<string, string[]>();
if (rawParams.length > 0) {
const params: string[] = rawParams.split('&');
params.forEach((param: string) => {
const eqIdx = param.indexOf('=');
const [key, val]: string[] = eqIdx == -1 ?
[codec.decodeKey(param), ''] :
[codec.decodeKey(param.slice(0, eqIdx)), codec.decodeValue(param.slice(eqIdx + 1))];
const list = map.get(key) || [];
list.push(val);
map.set(key, list);
});
}
return map;
}
function standardEncoding(v: string): string {
return encodeURIComponent(v)
.replace(/%40/gi, '@')
.replace(/%3A/gi, ':')
.replace(/%24/gi, '$')
.replace(/%2C/gi, ',')
.replace(/%3B/gi, ';')
.replace(/%2B/gi, '+')
.replace(/%3D/gi, '=')
.replace(/%3F/gi, '?')
.replace(/%2F/gi, '/');
}
interface Update {
param: string;
value?: string;
op: 'a'|'d'|'s';
}
/**
* An HTTP request/response body that represents serialized parameters in urlencoded form,
* per the MIME type `application/x-www-form-urlencoded`.
*
* This class is immuatable - all mutation operations return a new instance.
*
* @experimental
*/
export class HttpUrlEncodedBody {
private map: Map<string, string[]>|null;
private encoder: HttpUrlParameterCodec;
private updates: Update[]|null = null;
private cloneFrom: HttpUrlEncodedBody|null = null;
constructor(options: {
fromString?: string,
encoder?: HttpUrlParameterCodec,
} = {}) {
(this as any)['__HttpUrlEncodedBody'] = true;
this.encoder = options.encoder || new HttpStandardUrlParameterCodec();
this.map = !!options.fromString ? paramParser(options.fromString, this.encoder) : null;
}
/**
* Check whether the body has one or more values for the given parameter name.
*/
has(param: string): boolean {
this.init();
return this.map !.has(param);
}
/**
* Get the first value for the given parameter name, or `null` if it's not present.
*/
get(param: string): string|null {
this.init();
const res = this.map !.get(param);
return !!res ? res[0] : null;
}
/**
* Get all values for the given parameter name, or `null` if it's not present.
*/
getAll(param: string): string[]|null {
this.init();
return this.map !.get(param) || null;
}
/**
* Get all the parameter names for this body.
*/
params(): string[] {
this.init();
return Array.from(this.map !.keys());
}
/**
* Construct a new body with an appended value for the given parameter name.
*/
append(param: string, value: string): HttpUrlEncodedBody {
return this.clone({param, value, op: 'a'});
}
/**
* Construct a new body with a new value for the given parameter name.
*/
set(param: string, value: string): HttpUrlEncodedBody {
return this.clone({param, value, op: 's'});
}
/**
* Construct a new body with either the given value for the given parameter
* removed, if a value is given, or all values for the given parameter removed
* if not.
*/
delete (param: string, value?: string): HttpUrlEncodedBody {
return this.clone({param, value, op: 'd'});
}
/**
* Serialize the body to an encoded string, where key-value pairs (separated by `=`) are
* separated by `&`s.
*/
toString(): string {
this.init();
return this.params()
.map(key => {
const eKey = this.encoder.encodeKey(key);
return this.map !.get(key) !.map(value => eKey + '=' + this.encoder.encodeValue(value))
.join('&');
})
.join('&');
}
private clone(update: Update): HttpUrlEncodedBody {
const clone = new HttpUrlEncodedBody({encoder: this.encoder});
clone.cloneFrom = this.cloneFrom || this;
clone.updates = (this.updates || []).concat([update]);
return clone;
}
private init() {
if (this.map === null) {
this.map = new Map<string, string[]>();
}
if (this.cloneFrom !== null) {
this.cloneFrom.init();
this.cloneFrom.params().forEach(
key => this.map !.set(key, this.cloneFrom !.map !.get(key) !));
this.updates !.forEach(update => {
switch (update.op) {
case 'a':
case 's':
const base = (update.op === 'a' ? this.map !.get(update.param) : undefined) || [];
base.push(update.value !);
this.map !.set(update.param, base);
break;
case 'd':
if (update.value !== undefined) {
let base = this.map !.get(update.param) || [];
const idx = base.indexOf(update.value);
if (idx !== -1) {
base.splice(idx, 1);
}
if (base.length > 0) {
this.map !.set(update.param, base);
} else {
this.map !.delete(update.param);
}
} else {
this.map !.delete(update.param);
break;
}
}
});
this.cloneFrom = null;
}
}
}

View File

@ -0,0 +1,327 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Observer} from 'rxjs/Observer';
import {HttpBackend} from './backend';
import {HttpHeaders} from './headers';
import {HttpRequest} from './request';
import {HttpDownloadProgressEvent, HttpErrorResponse, HttpEvent, HttpEventType, HttpHeaderResponse, HttpJsonParseError, HttpResponse, HttpUploadProgressEvent} from './response';
const XSSI_PREFIX = /^\)\]\}',?\n/;
/**
* Determine an appropriate URL for the response, by checking either
* XMLHttpRequest.responseURL or the X-Request-URL header.
*/
function getResponseUrl(xhr: any): string|null {
if ('responseURL' in xhr && xhr.responseURL) {
return xhr.responseURL;
}
if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
return xhr.getResponseHeader('X-Request-URL');
}
return null;
}
/**
* A wrapper around the `XMLHttpRequest` constructor.
*
* @experimental
*/
export abstract class XhrFactory { abstract build(): XMLHttpRequest; }
/**
* A factory for @{link HttpXhrBackend} that uses the `XMLHttpRequest` browser API.
*
* @experimental
*/
@Injectable()
export class BrowserXhr implements XhrFactory {
constructor() {}
build(): any { return <any>(new XMLHttpRequest()); }
}
/**
* Tracks a response from the server that does not yet have a body.
*/
interface PartialResponse {
headers: HttpHeaders;
status: number;
statusText: string;
url: string;
}
/**
* An `HttpBackend` which uses the XMLHttpRequest API to send
* requests to a backend server.
*
* @experimental
*/
@Injectable()
export class HttpXhrBackend implements HttpBackend {
constructor(private xhrFactory: XhrFactory) {}
/**
* Process a request and return a stream of response events.
*/
handle(req: HttpRequest<any>): Observable<HttpEvent<any>> {
// Quick check to give a better error message when a user attempts to use
// HttpClient.jsonp() without installing the JsonpClientModule
if (req.method === 'JSONP') {
throw new Error(`Attempted to construct Jsonp request without JsonpClientModule installed.`);
}
// Everything happens on Observable subscription.
return new Observable((observer: Observer<HttpEvent<any>>) => {
// Start by setting up the XHR object with request method, URL, and withCredentials flag.
const xhr = this.xhrFactory.build();
xhr.open(req.method, req.url);
if (!!req.withCredentials) {
xhr.withCredentials = true;
}
// Add all the requested headers.
req.headers.forEach((name, values) => xhr.setRequestHeader(name, values.join(',')));
// Add an Accept header if one isn't present already.
if (!req.headers.has('Accept')) {
xhr.setRequestHeader('Accept', 'application/json, text/plain, */*');
}
// Auto-detect the Content-Type header if one isn't present already.
if (!req.headers.has('Content-Type')) {
const detectedType = req.detectContentTypeHeader();
// Sometimes Content-Type detection fails.
if (detectedType !== null) {
xhr.setRequestHeader('Content-Type', detectedType);
}
}
// Set the responseType if one was requested.
if (req.responseType) {
xhr.responseType = req.responseType.toLowerCase() as any;
}
// Serialize the request body if one is present. If not, this will be set to null.
const reqBody = req.serializeBody();
// If progress events are enabled, response headers will be delivered
// in two events - the HttpHeaderResponse event and the full HttpResponse
// event. However, since response headers don't change in between these
// two events, it doesn't make sense to parse them twice. So headerResponse
// caches the data extracted from the response whenever it's first parsed,
// to ensure parsing isn't duplicated.
let headerResponse: HttpHeaderResponse|null = null;
// partialFromXhr extracts the HttpHeaderResponse from the current XMLHttpRequest
// state, and memoizes it into headerResponse.
const partialFromXhr = (): HttpHeaderResponse => {
if (headerResponse !== null) {
return headerResponse;
}
// Read status and normalize an IE9 bug (http://bugs.jquery.com/ticket/1450).
const status: number = xhr.status === 1223 ? 204 : xhr.status;
const statusText = xhr.statusText || 'OK';
// Parse headers from XMLHttpRequest - this step is lazy.
const headers = new HttpHeaders(xhr.getAllResponseHeaders());
// Read the response URL from the XMLHttpResponse instance and fall back on the
// request URL.
const url = getResponseUrl(xhr) || req.url;
// Construct the HttpHeaderResponse and memoize it.
headerResponse = new HttpHeaderResponse({headers, status, statusText, url});
return headerResponse;
};
// Next, a few closures are defined for the various events which XMLHttpRequest can
// emit. This allows them to be unregistered as event listeners later.
// First up is the load event, which represents a response being fully available.
const onLoad = () => {
// Read response state from the memoized partial data.
let {headers, status, statusText, url} = partialFromXhr();
// The body will be read out if present.
let body: any|null = null;
if (status !== 204) {
// Use XMLHttpRequest.response if set, responseText otherwise.
body = (typeof xhr.response === 'undefined') ? xhr.responseText : xhr.response;
// Strip a common XSSI prefix from string responses.
// TODO: determine if this behavior should be optional and moved to an interceptor.
if (typeof body === 'string') {
body = body.replace(XSSI_PREFIX, '');
}
}
// Normalize another potential bug (this one comes from CORS).
if (status === 0) {
status = !!body ? 200 : 0;
}
// ok determines whether the response will be transmitted on the event or
// error channel. Unsuccessful status codes (not 2xx) will always be errors,
// but a successful status code can still result in an error if the user
// asked for JSON data and the body cannot be parsed as such.
let ok = status >= 200 && status < 300;
// Check whether the body needs to be parsed as JSON (in many cases the browser
// will have done that already).
if (ok && typeof body === 'string' && req.responseType === 'json') {
// Attempt the parse. If it fails, a parse error should be delivered to the user.
try {
body = JSON.parse(body);
} catch (error) {
// Even though the response status was 2xx, this is still an error.
ok = false;
// The parse error contains the text of the body that failed to parse.
body = { error, text: body } as HttpJsonParseError;
}
}
if (ok) {
// A successful response is delivered on the event stream.
observer.next(new HttpResponse({
body,
headers,
status,
statusText,
url: url || undefined,
}));
// The full body has been received and delivered, no further events
// are possible. This request is complete.
observer.complete();
} else {
// An unsuccessful request is delivered on the error channel.
observer.error(new HttpErrorResponse({
// The error in this case is the response body (error from the server).
error: body,
headers,
status,
statusText,
url: url || undefined,
}));
}
};
// The onError callback is called when something goes wrong at the network level.
// Connection timeout, DNS error, offline, etc. These are actual errors, and are
// transmitted on the error channel.
const onError = (error: ErrorEvent) => {
const res = new HttpErrorResponse({
error,
status: xhr.status || 0,
statusText: xhr.statusText || 'Unknown Error',
});
observer.error(res);
};
// The sentHeaders flag tracks whether the HttpResponseHeaders event
// has been sent on the stream. This is necessary to track if progress
// is enabled since the event will be sent on only the first download
// progerss event.
let sentHeaders = false;
// The download progress event handler, which is only registered if
// progress events are enabled.
const onDownProgress = (event: ProgressEvent) => {
// Send the HttpResponseHeaders event if it hasn't been sent already.
if (!sentHeaders) {
observer.next(partialFromXhr());
sentHeaders = true;
}
// Start building the download progress event to deliver on the response
// event stream.
let progressEvent: HttpDownloadProgressEvent = {
type: HttpEventType.DownloadProgress,
loaded: event.loaded,
};
// Set the total number of bytes in the event if it's available.
if (event.lengthComputable) {
progressEvent.total = event.total;
}
// If the request was for text content and a partial response is
// available on XMLHttpRequest, include it in the progress event
// to allow for streaming reads.
if (req.responseType === 'text' && !!xhr.responseText) {
progressEvent.partialText = xhr.responseText;
}
// Finally, fire the event.
observer.next(progressEvent);
};
// The upload progress event handler, which is only registered if
// progress events are enabled.
const onUpProgress =
(event: ProgressEvent) => {
// Upload progress events are simpler. Begin building the progress
// event.
let progress: HttpUploadProgressEvent = {
type: HttpEventType.UploadProgress,
loaded: event.loaded,
};
// If the total number of bytes being uploaded is available, include
// it.
if (event.lengthComputable) {
progress.total = event.total;
}
// Send the event.
observer.next(progress);
}
// By default, register for load and error events.
xhr.addEventListener('load', onLoad);
xhr.addEventListener('error', onError);
// Progress events are only enabled if requested.
if (req.reportProgress) {
// Download progress is always enabled if requested.
xhr.addEventListener('progress', onDownProgress);
// Upload progress depends on whether there is a body to upload.
if (reqBody !== null && xhr.upload) {
xhr.upload.addEventListener('progress', onUpProgress);
}
}
// Fire the request, and notify the event stream that it was fired.
xhr.send(reqBody);
observer.next({type: HttpEventType.Sent});
// This is the return from the Observable function, which is the
// request cancellation handler.
return () => {
// On a cancellation, remove all registered event listeners.
xhr.removeEventListener('error', onError);
xhr.removeEventListener('load', onLoad);
if (req.reportProgress) {
xhr.removeEventListener('progress', onDownProgress);
if (reqBody !== null && xhr.upload) {
xhr.upload.removeEventListener('progress', onUpProgress);
}
}
// Finally, abort the in-flight request.
xhr.abort();
};
});
}
}