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

@ -4807,7 +4807,7 @@
"version": "1.0.1" "version": "1.0.1"
}, },
"ts-api-guardian": { "ts-api-guardian": {
"version": "0.2.1", "version": "0.2.2",
"dependencies": { "dependencies": {
"diff": { "diff": {
"version": "2.2.3" "version": "2.2.3"

6
npm-shrinkwrap.json generated
View File

@ -7679,9 +7679,9 @@
"resolved": "https://registry.npmjs.org/trim-off-newlines/-/trim-off-newlines-1.0.1.tgz" "resolved": "https://registry.npmjs.org/trim-off-newlines/-/trim-off-newlines-1.0.1.tgz"
}, },
"ts-api-guardian": { "ts-api-guardian": {
"version": "0.2.1", "version": "0.2.2",
"from": "ts-api-guardian@0.2.1", "from": "ts-api-guardian@0.2.2",
"resolved": "https://registry.npmjs.org/ts-api-guardian/-/ts-api-guardian-0.2.1.tgz", "resolved": "https://registry.npmjs.org/ts-api-guardian/-/ts-api-guardian-0.2.2.tgz",
"dependencies": { "dependencies": {
"diff": { "diff": {
"version": "2.2.3", "version": "2.2.3",

View File

@ -92,7 +92,7 @@
"source-map": "^0.5.6", "source-map": "^0.5.6",
"source-map-support": "^0.4.2", "source-map-support": "^0.4.2",
"systemjs": "0.18.10", "systemjs": "0.18.10",
"ts-api-guardian": "^0.2.1", "ts-api-guardian": "^0.2.2",
"tsickle": "^0.21.1", "tsickle": "^0.21.1",
"tslint": "^4.1.1", "tslint": "^4.1.1",
"tslint-eslint-rules": "^3.1.0", "tslint-eslint-rules": "^3.1.0",

View File

@ -4,6 +4,7 @@ load("@io_bazel_rules_typescript//:defs.bzl", "ts_library")
ts_library( ts_library(
name = "common", name = "common",
srcs = glob(["**/*.ts"], exclude=[ srcs = glob(["**/*.ts"], exclude=[
"http/**",
"test/**", "test/**",
"testing/**", "testing/**",
]), ]),

View File

@ -0,0 +1,14 @@
/**
* @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
*/
// This file is not used to build this module. It is only used during editing
// by the TypeScript language service and during build for verification. `ngc`
// replaces this file with production index.ts when it rewrites private symbol
// names.
export * from './public_api';

View File

@ -0,0 +1,7 @@
{
"name": "@angular/common/http",
"typings": "../http.d.ts",
"main": "../bundles/common-http.umd.js",
"module": "../@angular/common/http.es5.js",
"es2015": "../@angular/common/http.js"
}

View File

@ -0,0 +1,18 @@
/**
* @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
*/
export {HttpBackend, HttpHandler} from './src/backend';
export {HttpClient} from './src/client';
export {HttpHeaders} from './src/headers';
export {HTTP_INTERCEPTORS, HttpInterceptor} from './src/interceptor';
export {JsonpClientBackend, JsonpInterceptor} from './src/jsonp';
export {HttpClientJsonpModule, HttpClientModule, interceptingHandler as ɵinterceptingHandler} from './src/module';
export {HttpRequest} from './src/request';
export {HttpDownloadProgressEvent, HttpErrorResponse, HttpEvent, HttpEventType, HttpHeaderResponse, HttpProgressEvent, HttpResponse, HttpResponseBase, HttpSentEvent, HttpUserEvent} from './src/response';
export {HttpStandardUrlParameterCodec, HttpUrlEncodedBody, HttpUrlParameterCodec} from './src/url_encoded_body';
export {HttpXhrBackend, XhrFactory} from './src/xhr';

View File

@ -0,0 +1,21 @@
/**
* @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
*/
export default {
entry: '../../../dist/packages-dist/common/@angular/common/http.es5.js',
dest: '../../../dist/packages-dist/common/bundles/common-http.umd.js',
format: 'umd',
exports: 'named',
moduleName: 'ng.commmon.http',
globals: {
'@angular/core': 'ng.core',
'@angular/platform-browser': 'ng.platformBrowser',
'rxjs/Observable': 'Rx',
'rxjs/Subject': 'Rx'
}
};

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();
};
});
}
}

View File

@ -0,0 +1,114 @@
/**
* @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 'rxjs/add/operator/toArray';
import 'rxjs/add/operator/toPromise';
import {ddescribe, describe, iit, it} from '@angular/core/testing/src/testing_internal';
import {HttpClient} from '../src/client';
import {HttpEventType, HttpResponse} from '../src/response';
import {HttpClientTestingBackend} from '../testing/src/backend';
export function main() {
describe('HttpClient', () => {
let client: HttpClient = null !;
let backend: HttpClientTestingBackend = null !;
beforeEach(() => {
backend = new HttpClientTestingBackend();
client = new HttpClient(backend);
});
afterEach(() => { backend.verify(); });
describe('makes a basic request', () => {
it('for JSON data', (done: DoneFn) => {
client.get('/test').subscribe(res => {
expect((res as any)['data']).toEqual('hello world');
done();
});
backend.expectOne('/test').flush({'data': 'hello world'});
});
it('for text data', (done: DoneFn) => {
client.get('/test', {responseType: 'text'}).subscribe(res => {
expect(res).toEqual('hello world');
done();
});
backend.expectOne('/test').flush('hello world');
});
it('for an arraybuffer', (done: DoneFn) => {
const body = new ArrayBuffer(4);
client.get('/test', {responseType: 'arraybuffer'}).subscribe(res => {
expect(res).toBe(body);
done();
});
backend.expectOne('/test').flush(body);
});
if (typeof Blob !== 'undefined') {
it('for a blob', (done: DoneFn) => {
const body = new Blob([new ArrayBuffer(4)]);
client.get('/test', {responseType: 'blob'}).subscribe(res => {
expect(res).toBe(body);
done();
});
backend.expectOne('/test').flush(body);
});
}
it('that returns a response', (done: DoneFn) => {
const body = {'data': 'hello world'};
client.get('/test', {observe: 'response'}).subscribe(res => {
expect(res instanceof HttpResponse).toBe(true);
expect(res.body).toBe(body);
done();
});
backend.expectOne('/test').flush(body);
});
it('that returns a stream of events', (done: DoneFn) => {
client.get('/test', {observe: 'events'}).toArray().toPromise().then(events => {
expect(events.length).toBe(2);
expect(events[0].type).toBe(HttpEventType.Sent);
expect(events[1].type).toBe(HttpEventType.Response);
expect(events[1] instanceof HttpResponse).toBeTruthy();
done();
});
backend.expectOne('/test').flush({'data': 'hello world'});
});
});
describe('makes a POST request', () => {
it('with text data', (done: DoneFn) => {
client.post('/test', 'text body', {observe: 'response', responseType: 'text'})
.subscribe(res => {
expect(res.ok).toBeTruthy();
expect(res.status).toBe(200);
done();
});
backend.expectOne('/test').flush('hello world');
});
it('with json data', (done: DoneFn) => {
const body = {data: 'json body'};
client.post('/test', body, {observe: 'response', responseType: 'text'}).subscribe(res => {
expect(res.ok).toBeTruthy();
expect(res.status).toBe(200);
done();
});
const testReq = backend.expectOne('/test');
expect(testReq.request.body).toBe(body);
testReq.flush('hello world');
});
it('with an arraybuffer', (done: DoneFn) => {
const body = new ArrayBuffer(4);
client.post('/test', body, {observe: 'response', responseType: 'text'}).subscribe(res => {
expect(res.ok).toBeTruthy();
expect(res.status).toBe(200);
done();
});
const testReq = backend.expectOne('/test');
expect(testReq.request.body).toBe(body);
testReq.flush('hello world');
});
});
});
}

View File

@ -0,0 +1,144 @@
/**
* @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 '../src/headers';
export function main() {
describe('HttpHeaders', () => {
describe('initialization', () => {
it('should conform to spec', () => {
const httpHeaders = {
'Content-Type': 'image/jpeg',
'Accept-Charset': 'utf-8',
'X-My-Custom-Header': 'Zeke are cool',
};
const secondHeaders = new HttpHeaders(httpHeaders);
expect(secondHeaders.get('Content-Type')).toEqual('image/jpeg');
});
it('should merge values in provided dictionary', () => {
const headers = new HttpHeaders({'foo': 'bar'});
expect(headers.get('foo')).toEqual('bar');
expect(headers.getAll('foo')).toEqual(['bar']);
});
it('should lazily append values', () => {
const src = new HttpHeaders();
const a = src.append('foo', 'a');
const b = a.append('foo', 'b');
const c = b.append('foo', 'c');
expect(src.getAll('foo')).toBeNull();
expect(a.getAll('foo')).toEqual(['a']);
expect(b.getAll('foo')).toEqual(['a', 'b']);
expect(c.getAll('foo')).toEqual(['a', 'b', 'c']);
});
it('should keep the last value when initialized from an object', () => {
const headers = new HttpHeaders({
'foo': 'first',
'fOo': 'second',
});
expect(headers.getAll('foo')).toEqual(['second']);
});
});
describe('.set()', () => {
it('should clear all values and re-set for the provided key', () => {
const headers = new HttpHeaders({'foo': 'bar'});
expect(headers.get('foo')).toEqual('bar');
const second = headers.set('foo', 'baz');
expect(second.get('foo')).toEqual('baz');
const third = headers.set('fOO', 'bat');
expect(third.get('foo')).toEqual('bat');
});
it('should preserve the case of the first call', () => {
const headers = new HttpHeaders();
const second = headers.set('fOo', 'baz');
const third = second.set('foo', 'bat');
expect(third.keys()).toEqual(['fOo']);
});
});
describe('.get()', () => {
it('should be case insensitive', () => {
const headers = new HttpHeaders({'foo': 'baz'});
expect(headers.get('foo')).toEqual('baz');
expect(headers.get('FOO')).toEqual('baz');
});
it('should return null if the header is not present', () => {
const headers = new HttpHeaders({bar: []});
expect(headers.get('bar')).toEqual(null);
expect(headers.get('foo')).toEqual(null);
});
});
describe('.getAll()', () => {
it('should be case insensitive', () => {
const headers = new HttpHeaders({foo: ['bar', 'baz']});
expect(headers.getAll('foo')).toEqual(['bar', 'baz']);
expect(headers.getAll('FOO')).toEqual(['bar', 'baz']);
});
it('should return null if the header is not present', () => {
const headers = new HttpHeaders();
expect(headers.getAll('foo')).toEqual(null);
});
});
describe('.delete', () => {
it('should be case insensitive', () => {
const headers = new HttpHeaders({'foo': 'baz'});
expect(headers.has('foo')).toEqual(true);
const second = headers.delete('foo');
expect(second.has('foo')).toEqual(false);
const third = second.set('foo', 'baz');
expect(third.has('foo')).toEqual(true);
const fourth = third.delete('FOO');
expect(fourth.has('foo')).toEqual(false);
});
});
describe('.append', () => {
it('should append a value to the list', () => {
const headers = new HttpHeaders();
const second = headers.append('foo', 'bar');
const third = second.append('foo', 'baz');
expect(third.get('foo')).toEqual('bar');
expect(third.getAll('foo')).toEqual(['bar', 'baz']);
});
it('should preserve the case of the first call', () => {
const headers = new HttpHeaders();
const second = headers.append('FOO', 'bar');
const third = second.append('foo', 'baz');
expect(third.keys()).toEqual(['FOO']);
});
});
describe('response header strings', () => {
it('should be parsed by the constructor', () => {
const response = `Date: Fri, 20 Nov 2015 01:45:26 GMT\n` +
`Content-Type: application/json; charset=utf-8\n` +
`Transfer-Encoding: chunked\n` +
`Connection: keep-alive`;
const headers = new HttpHeaders(response);
expect(headers.get('Date')).toEqual('Fri, 20 Nov 2015 01:45:26 GMT');
expect(headers.get('Content-Type')).toEqual('application/json; charset=utf-8');
expect(headers.get('Transfer-Encoding')).toEqual('chunked');
expect(headers.get('Connection')).toEqual('keep-alive');
});
});
});
}

View File

@ -0,0 +1,44 @@
/**
* @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
*/
export class MockScriptElement {
constructor() {}
listeners: {
load?: (event: Event) => void,
error?: (err: Error) => void,
} = {};
addEventListener(event: 'load'|'error', handler: Function): void {
this.listeners[event] = handler as any;
}
removeEventListener(event: 'load'|'error'): void { delete this.listeners[event]; }
}
export class MockDocument {
mock: MockScriptElement|null;
createElement(tag: 'script'): HTMLScriptElement {
return new MockScriptElement() as any as HTMLScriptElement;
}
get body(): any { return this; }
appendChild(node: any): void { this.mock = node; }
removeNode(node: any): void {
if (this.mock === node) {
this.mock = null;
}
}
mockLoad(): void { this.mock !.listeners.load !(null as any); }
mockError(err: Error) { this.mock !.listeners.error !(err); }
}

View File

@ -0,0 +1,75 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.JsonpCallbackContext
*
* 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 {ddescribe, describe, it} from '@angular/core/testing/src/testing_internal';
import {JSONP_ERR_NO_CALLBACK, JSONP_ERR_WRONG_METHOD, JSONP_ERR_WRONG_RESPONSE_TYPE, JsonpClientBackend} from '../src/jsonp';
import {HttpRequest} from '../src/request';
import {HttpErrorResponse, HttpEventType} from '../src/response';
import {MockDocument} from './jsonp_mock';
function runOnlyCallback(home: any, data: Object) {
const keys = Object.keys(home);
expect(keys.length).toBe(1);
const callback = home[keys[0]];
delete home[keys[0]];
callback(data);
}
const SAMPLE_REQ = new HttpRequest<never>('JSONP', '/test');
export function main() {
describe('JsonpClientBackend', () => {
let home = {};
let document: MockDocument;
let backend: JsonpClientBackend;
beforeEach(() => {
home = {};
document = new MockDocument();
backend = new JsonpClientBackend(home, document);
});
it('handles a basic request', (done: DoneFn) => {
backend.handle(SAMPLE_REQ).toArray().subscribe(events => {
expect(events.map(event => event.type)).toEqual([
HttpEventType.Sent,
HttpEventType.Response,
]);
done();
});
runOnlyCallback(home, {data: 'This is a test'});
document.mockLoad();
});
it('handles an error response properly', (done: DoneFn) => {
const error = new Error('This is a test error');
backend.handle(SAMPLE_REQ).toArray().subscribe(undefined, (err: HttpErrorResponse) => {
expect(err.status).toBe(0);
expect(err.error).toBe(error);
done();
});
document.mockError(error);
});
describe('throws an error', () => {
it('when request method is not JSONP',
() => {expect(() => backend.handle(SAMPLE_REQ.clone<never>({method: 'GET'})))
.toThrowError(JSONP_ERR_WRONG_METHOD)});
it('when response type is not json',
() => {expect(() => backend.handle(SAMPLE_REQ.clone<never>({responseType: 'text'})))
.toThrowError(JSONP_ERR_WRONG_RESPONSE_TYPE)});
it('when callback is never called', (done: DoneFn) => {
backend.handle(SAMPLE_REQ).subscribe(undefined, (err: HttpErrorResponse) => {
expect(err.status).toBe(0);
expect(err.error instanceof Error).toEqual(true);
expect(err.error.message).toEqual(JSONP_ERR_NO_CALLBACK);
done();
});
document.mockLoad();
})
});
});
}

View File

@ -0,0 +1,88 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.JsonpCallbackContext
*
* 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 'rxjs/add/operator/map';
import {Injector} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {Observable} from 'rxjs/Observable';
import {HttpHandler} from '../src/backend';
import {HttpClient} from '../src/client';
import {HTTP_INTERCEPTORS, HttpInterceptor} from '../src/interceptor';
import {HttpRequest} from '../src/request';
import {HttpEvent, HttpResponse} from '../src/response';
import {HttpTestingController} from '../testing/src/api';
import {HttpClientTestingModule} from '../testing/src/module';
import {TestRequest} from '../testing/src/request';
class TestInterceptor implements HttpInterceptor {
constructor(private value: string) {}
intercept(req: HttpRequest<any>, delegate: HttpHandler): Observable<HttpEvent<any>> {
const existing = req.headers.get('Intercepted');
const next = !!existing ? existing + ',' + this.value : this.value;
req = req.clone({setHeaders: {'Intercepted': next}});
return delegate.handle(req).map(event => {
if (event instanceof HttpResponse) {
const existing = event.headers.get('Intercepted');
const next = !!existing ? existing + ',' + this.value : this.value;
return event.clone({headers: event.headers.set('Intercepted', next)});
}
return event;
});
}
}
class InterceptorA extends TestInterceptor {
constructor() { super('A'); }
}
class InterceptorB extends TestInterceptor {
constructor() { super('B'); }
}
export function main() {
describe('HttpClientModule', () => {
let injector: Injector;
beforeEach(() => {
injector = TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
{provide: HTTP_INTERCEPTORS, useClass: InterceptorA, multi: true},
{provide: HTTP_INTERCEPTORS, useClass: InterceptorB, multi: true},
],
});
});
it('initializes HttpClient properly', (done: DoneFn) => {
injector.get(HttpClient).get('/test', {responseType: 'text'}).subscribe(value => {
expect(value).toBe('ok!');
done();
});
injector.get(HttpTestingController).expectOne('/test').flush('ok!');
});
it('intercepts outbound responses in the order in which interceptors were bound',
(done: DoneFn) => {
injector.get(HttpClient)
.get('/test', {observe: 'response', responseType: 'text'})
.subscribe(value => done());
const req = injector.get(HttpTestingController).expectOne('/test') as TestRequest;
expect(req.request.headers.get('Intercepted')).toEqual('A,B');
req.flush('ok!');
});
it('intercepts inbound responses in the right (reverse binding) order', (done: DoneFn) => {
injector.get(HttpClient)
.get('/test', {observe: 'response', responseType: 'text'})
.subscribe(value => {
expect(value.headers.get('Intercepted')).toEqual('B,A');
done();
});
injector.get(HttpTestingController).expectOne('/test').flush('ok!');
});
});
}

View File

@ -0,0 +1,136 @@
/**
* @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 {ddescribe, describe, it} from '@angular/core/testing/src/testing_internal';
import {HttpHeaders} from '../src/headers';
import {HttpRequest} from '../src/request';
const TEST_URL = 'http://angular.io';
const TEST_STRING = `I'm a body!`;
export function main() {
describe('HttpRequest', () => {
describe('constructor', () => {
it('initializes url', () => {
const req = new HttpRequest('', TEST_URL, null);
expect(req.url).toBe(TEST_URL);
});
it('doesn\'t require a body for body-less methods', () => {
let req = new HttpRequest('GET', TEST_URL);
expect(req.method).toBe('GET');
expect(req.body).toBeNull();
req = new HttpRequest('HEAD', TEST_URL);
expect(req.method).toBe('HEAD');
expect(req.body).toBeNull();
req = new HttpRequest('JSONP', TEST_URL);
expect(req.method).toBe('JSONP');
expect(req.body).toBeNull();
req = new HttpRequest('OPTIONS', TEST_URL);
expect(req.method).toBe('OPTIONS');
expect(req.body).toBeNull();
});
it('accepts a string request method', () => {
const req = new HttpRequest('TEST', TEST_URL, null);
expect(req.method).toBe('TEST');
});
it('accepts a string body', () => {
const req = new HttpRequest('POST', TEST_URL, TEST_STRING);
expect(req.body).toBe(TEST_STRING);
});
it('accepts an object body', () => {
const req = new HttpRequest('POST', TEST_URL, {data: TEST_STRING});
expect(req.body).toEqual({data: TEST_STRING});
});
it('creates default headers if not passed', () => {
const req = new HttpRequest('GET', TEST_URL);
expect(req.headers instanceof HttpHeaders).toBeTruthy();
});
it('uses the provided headers if passed', () => {
const headers = new HttpHeaders();
const req = new HttpRequest('GET', TEST_URL, {headers});
expect(req.headers).toBe(headers);
});
it('defaults to Json', () => {
const req = new HttpRequest('GET', TEST_URL);
expect(req.responseType).toBe('json');
});
});
describe('clone() copies the request', () => {
const headers = new HttpHeaders({
'Test': 'Test header',
});
const req = new HttpRequest('POST', TEST_URL, 'test body', {
headers,
reportProgress: true,
responseType: 'text',
withCredentials: true,
});
it('in the base case', () => {
const clone = req.clone();
expect(clone.method).toBe('POST');
expect(clone.responseType).toBe('text');
expect(clone.url).toBe(TEST_URL);
// Headers should be the same, as the headers are sealed.
expect(clone.headers).toBe(headers);
expect(clone.headers.get('Test')).toBe('Test header');
});
it('and updates the url',
() => { expect(req.clone({url: '/changed'}).url).toBe('/changed'); });
it('and updates the method',
() => { expect(req.clone({method: 'PUT'}).method).toBe('PUT'); });
it('and updates the body',
() => { expect(req.clone({body: 'changed body'}).body).toBe('changed body'); });
});
describe('content type detection', () => {
const baseReq = new HttpRequest('POST', '/test', null);
it('handles a null body', () => { expect(baseReq.detectContentTypeHeader()).toBeNull(); });
it('doesn\'t associate a content type with ArrayBuffers', () => {
const req = baseReq.clone({body: new ArrayBuffer(4)});
expect(req.detectContentTypeHeader()).toBeNull();
});
it('handles strings as text', () => {
const req = baseReq.clone({body: 'hello world'});
expect(req.detectContentTypeHeader()).toBe('text/plain');
});
it('handles arrays as json', () => {
const req = baseReq.clone({body: ['a', 'b']});
expect(req.detectContentTypeHeader()).toBe('application/json');
});
it('handles numbers as json', () => {
const req = baseReq.clone({body: 314159});
expect(req.detectContentTypeHeader()).toBe('application/json');
});
it('handles objects as json', () => {
const req = baseReq.clone({body: {data: 'test data'}});
expect(req.detectContentTypeHeader()).toBe('application/json');
});
});
describe('body serialization', () => {
const baseReq = new HttpRequest('POST', '/test', null);
it('handles a null body', () => { expect(baseReq.serializeBody()).toBeNull(); });
it('passes ArrayBuffers through', () => {
const body = new ArrayBuffer(4);
expect(baseReq.clone({body}).serializeBody()).toBe(body);
});
it('passes strings through', () => {
const body = 'hello world';
expect(baseReq.clone({body}).serializeBody()).toBe(body);
});
it('serializes arrays as json', () => {
expect(baseReq.clone({body: ['a', 'b']}).serializeBody()).toBe('["a","b"]');
});
it('handles numbers as json',
() => { expect(baseReq.clone({body: 314159}).serializeBody()).toBe('314159'); });
it('handles objects as json', () => {
const req = baseReq.clone({body: {data: 'test data'}});
expect(req.serializeBody()).toBe('{"data":"test data"}');
});
});
});
}

View File

@ -0,0 +1,78 @@
/**
* @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 {ddescribe, describe, it} from '@angular/core/testing/src/testing_internal';
import {HttpHeaders} from '../src/headers';
import {HttpResponse} from '../src/response';
export function main() {
describe('HttpResponse', () => {
describe('constructor()', () => {
it('fully constructs responses', () => {
const resp = new HttpResponse({
body: 'test body',
headers: new HttpHeaders({
'Test': 'Test header',
}),
status: 201,
statusText: 'Created',
url: '/test',
});
expect(resp.body).toBe('test body');
expect(resp.headers instanceof HttpHeaders).toBeTruthy();
expect(resp.headers.get('Test')).toBe('Test header');
expect(resp.status).toBe(201);
expect(resp.statusText).toBe('Created');
expect(resp.url).toBe('/test');
});
it('uses defaults if no args passed', () => {
const resp = new HttpResponse({});
expect(resp.headers).not.toBeNull();
expect(resp.status).toBe(200);
expect(resp.statusText).toBe('OK');
expect(resp.body).toBeNull();
expect(resp.ok).toBeTruthy();
expect(resp.url).toBeNull();
});
});
it('.ok is determined by status', () => {
const good = new HttpResponse({status: 200});
const alsoGood = new HttpResponse({status: 299});
const badHigh = new HttpResponse({status: 300});
const badLow = new HttpResponse({status: 199});
expect(good.ok).toBe(true);
expect(alsoGood.ok).toBe(true);
expect(badHigh.ok).toBe(false);
expect(badLow.ok).toBe(false);
});
describe('.clone()', () => {
it('copies the original when given no arguments', () => {
const clone =
new HttpResponse({body: 'test', status: 201, statusText: 'created', url: '/test'})
.clone();
expect(clone.body).toBe('test');
expect(clone.status).toBe(201);
expect(clone.statusText).toBe('created');
expect(clone.url).toBe('/test');
expect(clone.headers).not.toBeNull();
});
it('overrides the original', () => {
const orig =
new HttpResponse({body: 'test', status: 201, statusText: 'created', url: '/test'});
const clone =
orig.clone({body: {data: 'test'}, status: 200, statusText: 'Okay', url: '/bar'});
expect(clone.body).toEqual({data: 'test'});
expect(clone.status).toBe(200);
expect(clone.statusText).toBe('Okay');
expect(clone.url).toBe('/bar');
expect(clone.headers).toBe(orig.headers);
});
});
});
}

View File

@ -0,0 +1,76 @@
/**
* @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 {HttpUrlEncodedBody} from '../src/url_encoded_body';
export function main() {
describe('HttpUrlEncodedBody', () => {
describe('initialization', () => {
it('should be empty at construction', () => {
const body = new HttpUrlEncodedBody();
expect(body.toString()).toEqual('')
});
it('should parse an existing url', () => {
const body = new HttpUrlEncodedBody({fromString: 'a=b&c=d&c=e'});
expect(body.getAll('a')).toEqual(['b']);
expect(body.getAll('c')).toEqual(['d', 'e']);
});
});
describe('lazy mutation', () => {
it('should allow setting parameters', () => {
const body = new HttpUrlEncodedBody({fromString: 'a=b'});
const mutated = body.set('a', 'c');
expect(mutated.toString()).toEqual('a=c');
});
it('should allow appending parameters', () => {
const body = new HttpUrlEncodedBody({fromString: 'a=b'});
const mutated = body.append('a', 'c');
expect(mutated.toString()).toEqual('a=b&a=c');
});
it('should allow deletion of parameters', () => {
const body = new HttpUrlEncodedBody({fromString: 'a=b&c=d&e=f'});
const mutated = body.delete('c');
expect(mutated.toString()).toEqual('a=b&e=f');
});
it('should allow chaining of mutations', () => {
const body = new HttpUrlEncodedBody({fromString: 'a=b&c=d&e=f'});
const mutated = body.append('e', 'y').delete('c').set('a', 'x').append('e', 'z');
expect(mutated.toString()).toEqual('a=x&e=f&e=y&e=z');
});
it('should allow deletion of one value of a parameter', () => {
const body = new HttpUrlEncodedBody({fromString: 'a=1&a=2&a=3&a=4&a=5'});
const mutated = body.delete('a', '2').delete('a', '4');
expect(mutated.getAll('a')).toEqual(['1', '3', '5']);
});
});
describe('read operations', () => {
it('should give null if parameter is not set', () => {
const body = new HttpUrlEncodedBody({fromString: 'a=b&c=d'});
expect(body.get('e')).toBeNull();
expect(body.getAll('e')).toBeNull();
});
it('should give an accurate list of keys', () => {
const body = new HttpUrlEncodedBody({fromString: 'a=1&b=2&c=3&d=4'});
expect(body.params()).toEqual(['a', 'b', 'c', 'd']);
});
});
it('should have a magic Symbol-like property', () => {
const body = new HttpUrlEncodedBody() as any;
expect(body['__HttpUrlEncodedBody']).toEqual(true);
});
});
}

View File

@ -0,0 +1,119 @@
/**
* @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 '../src/headers';
import {XhrFactory} from '../src/xhr';
export class MockXhrFactory implements XhrFactory {
mock: MockXMLHttpRequest;
build(): XMLHttpRequest { return (this.mock = new MockXMLHttpRequest()) as any; }
}
export class MockXMLHttpRequestUpload {
constructor(private mock: MockXMLHttpRequest) {}
addEventListener(event: 'progress', handler: Function) {
this.mock.addEventListener('uploadProgress', handler);
}
removeEventListener(event: 'progress', handler: Function) {
this.mock.removeEventListener('uploadProgress');
}
}
export class MockXMLHttpRequest {
// Set by method calls.
body: any;
method: string;
url: string;
mockHeaders: {[key: string]: string} = {};
mockAborted: boolean = false;
// Directly settable interface.
withCredentials: boolean = false;
responseType: string = 'text';
// Mocked response interface.
response: any|undefined = undefined;
responseText: string|undefined = undefined;
responseURL: string|null = null;
status: number = 0;
statusText: string = '';
mockResponseHeaders: string = '';
listeners: {
error?: (event: ErrorEvent) => void,
load?: () => void,
progress?: (event: ProgressEvent) => void,
uploadProgress?: (event: ProgressEvent) => void,
} = {};
upload = new MockXMLHttpRequestUpload(this);
open(method: string, url: string): void {
this.method = method;
this.url = url;
}
send(body: any): void { this.body = body; }
addEventListener(event: 'error'|'load'|'progress'|'uploadProgress', handler: Function): void {
this.listeners[event] = handler as any;
}
removeEventListener(event: 'error'|'load'|'progress'|'uploadProgress'): void {
delete this.listeners[event];
}
setRequestHeader(name: string, value: string): void { this.mockHeaders[name] = value; }
getAllResponseHeaders(): string { return this.mockResponseHeaders; }
getResponseHeader(header: string): string|null {
return new HttpHeaders(this.mockResponseHeaders).get(header);
}
mockFlush(status: number, statusText: string, body: any|null) {
if (this.responseType === 'text') {
this.responseText = body;
} else {
this.response = body;
}
this.status = status;
this.statusText = statusText;
this.mockLoadEvent();
}
mockDownloadProgressEvent(loaded: number, total?: number): void {
if (this.listeners.progress) {
this.listeners.progress({ lengthComputable: total !== undefined, loaded, total } as any);
}
}
mockUploadProgressEvent(loaded: number, total?: number) {
if (this.listeners.uploadProgress) {
this.listeners.uploadProgress(
{ lengthComputable: total !== undefined, loaded, total, } as any);
}
}
mockLoadEvent(): void {
if (this.listeners.load) {
this.listeners.load();
}
}
mockErrorEvent(error: any): void {
if (this.listeners.error) {
this.listeners.error(error);
}
}
abort() { this.mockAborted = true; }
}

View File

@ -0,0 +1,306 @@
/**
* @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 {ddescribe, describe, it} from '@angular/core/testing/src/testing_internal';
import {Observable} from 'rxjs/Observable';
import {HttpRequest} from '../src/request';
import {HttpDownloadProgressEvent, HttpErrorResponse, HttpEvent, HttpEventType, HttpHeaderResponse, HttpResponse, HttpResponseBase, HttpUploadProgressEvent} from '../src/response';
import {HttpXhrBackend} from '../src/xhr';
import {MockXhrFactory} from './xhr_mock';
function trackEvents(obs: Observable<HttpEvent<any>>): HttpEvent<any>[] {
const events: HttpEvent<any>[] = [];
obs.subscribe(event => events.push(event));
return events;
}
const TEST_POST = new HttpRequest('POST', '/test', 'some body', {
responseType: 'text',
});
export function main() {
describe('XhrBackend', () => {
let factory: MockXhrFactory = null !;
let backend: HttpXhrBackend = null !;
beforeEach(() => {
factory = new MockXhrFactory();
backend = new HttpXhrBackend(factory);
});
it('emits status immediately', () => {
const events = trackEvents(backend.handle(TEST_POST));
expect(events.length).toBe(1);
expect(events[0].type).toBe(HttpEventType.Sent);
});
it('sets method, url, and responseType correctly', () => {
backend.handle(TEST_POST).subscribe();
expect(factory.mock.method).toBe('POST');
expect(factory.mock.responseType).toBe('text');
expect(factory.mock.url).toBe('/test');
});
it('sets outgoing body correctly', () => {
backend.handle(TEST_POST).subscribe();
expect(factory.mock.body).toBe('some body');
});
it('sets outgoing headers, including default headers', () => {
const post = TEST_POST.clone({
setHeaders: {
'Test': 'Test header',
},
});
backend.handle(post).subscribe();
expect(factory.mock.mockHeaders).toEqual({
'Test': 'Test header',
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'text/plain',
});
});
it('sets outgoing headers, including overriding defaults', () => {
const setHeaders = {
'Test': 'Test header',
'Accept': 'text/html',
'Content-Type': 'text/css',
};
backend.handle(TEST_POST.clone({setHeaders})).subscribe();
expect(factory.mock.mockHeaders).toEqual(setHeaders);
});
it('passes withCredentials through', () => {
backend.handle(TEST_POST.clone({withCredentials: true})).subscribe();
expect(factory.mock.withCredentials).toBe(true);
});
it('handles a text response', () => {
const events = trackEvents(backend.handle(TEST_POST));
factory.mock.mockFlush(200, 'OK', 'some response');
expect(events.length).toBe(2);
expect(events[1].type).toBe(HttpEventType.Response);
expect(events[1] instanceof HttpResponse).toBeTruthy();
const res = events[1] as HttpResponse<string>;
expect(res.body).toBe('some response');
expect(res.status).toBe(200);
expect(res.statusText).toBe('OK');
});
it('handles a json response', () => {
const events = trackEvents(backend.handle(TEST_POST.clone({responseType: 'json'})));
factory.mock.mockFlush(200, 'OK', {data: 'some data'});
expect(events.length).toBe(2);
const res = events[1] as HttpResponse<{data: string}>;
expect(res.body !.data).toBe('some data');
});
it('handles a json response that comes via responseText', () => {
const events = trackEvents(backend.handle(TEST_POST.clone({responseType: 'json'})));
factory.mock.mockFlush(200, 'OK', JSON.stringify({data: 'some data'}));
expect(events.length).toBe(2);
const res = events[1] as HttpResponse<{data: string}>;
expect(res.body !.data).toBe('some data');
});
it('emits unsuccessful responses via the error path', (done: DoneFn) => {
backend.handle(TEST_POST).subscribe(undefined, (err: HttpErrorResponse) => {
expect(err instanceof HttpErrorResponse).toBe(true);
expect(err.error).toBe('this is the error');
done();
});
factory.mock.mockFlush(400, 'Bad Request', 'this is the error');
});
it('emits real errors via the error path', (done: DoneFn) => {
backend.handle(TEST_POST).subscribe(undefined, (err: HttpErrorResponse) => {
expect(err instanceof HttpErrorResponse).toBe(true);
expect(err.error instanceof Error);
done();
});
factory.mock.mockErrorEvent(new Error('blah'));
});
describe('progress events', () => {
it('are emitted for download progress', (done: DoneFn) => {
backend.handle(TEST_POST.clone({reportProgress: true})).toArray().subscribe(events => {
expect(events.map(event => event.type)).toEqual([
HttpEventType.Sent,
HttpEventType.ResponseHeader,
HttpEventType.DownloadProgress,
HttpEventType.DownloadProgress,
HttpEventType.Response,
]);
const [progress1, progress2, response] = [
events[2] as HttpDownloadProgressEvent, events[3] as HttpDownloadProgressEvent,
events[4] as HttpResponse<string>
];
expect(progress1.partialText).toBe('down');
expect(progress1.loaded).toBe(100);
expect(progress1.total).toBe(300);
expect(progress2.partialText).toBe('download');
expect(progress2.loaded).toBe(200);
expect(progress2.total).toBe(300);
expect(response.body).toBe('downloaded');
done();
});
factory.mock.responseText = 'down';
factory.mock.mockDownloadProgressEvent(100, 300);
factory.mock.responseText = 'download';
factory.mock.mockDownloadProgressEvent(200, 300);
factory.mock.mockFlush(200, 'OK', 'downloaded');
});
it('are emitted for upload progress', (done: DoneFn) => {
backend.handle(TEST_POST.clone({reportProgress: true})).toArray().subscribe(events => {
expect(events.map(event => event.type)).toEqual([
HttpEventType.Sent,
HttpEventType.UploadProgress,
HttpEventType.UploadProgress,
HttpEventType.Response,
]);
const [progress1, progress2] = [
events[1] as HttpUploadProgressEvent,
events[2] as HttpUploadProgressEvent,
];
expect(progress1.loaded).toBe(100);
expect(progress1.total).toBe(300);
expect(progress2.loaded).toBe(200);
expect(progress2.total).toBe(300);
done();
});
factory.mock.mockUploadProgressEvent(100, 300);
factory.mock.mockUploadProgressEvent(200, 300);
factory.mock.mockFlush(200, 'OK', 'Done');
});
it('are emitted when both upload and download progress are available', (done: DoneFn) => {
backend.handle(TEST_POST.clone({reportProgress: true})).toArray().subscribe(events => {
expect(events.map(event => event.type)).toEqual([
HttpEventType.Sent,
HttpEventType.UploadProgress,
HttpEventType.ResponseHeader,
HttpEventType.DownloadProgress,
HttpEventType.Response,
]);
done();
});
factory.mock.mockUploadProgressEvent(100, 300);
factory.mock.mockDownloadProgressEvent(200, 300);
factory.mock.mockFlush(200, 'OK', 'Done');
});
it('are emitted even if length is not computable', (done: DoneFn) => {
backend.handle(TEST_POST.clone({reportProgress: true})).toArray().subscribe(events => {
expect(events.map(event => event.type)).toEqual([
HttpEventType.Sent,
HttpEventType.UploadProgress,
HttpEventType.ResponseHeader,
HttpEventType.DownloadProgress,
HttpEventType.Response,
]);
done();
});
factory.mock.mockUploadProgressEvent(100);
factory.mock.mockDownloadProgressEvent(200);
factory.mock.mockFlush(200, 'OK', 'Done');
});
it('include ResponseHeader with headers and status', (done: DoneFn) => {
backend.handle(TEST_POST.clone({reportProgress: true})).toArray().subscribe(events => {
expect(events.map(event => event.type)).toEqual([
HttpEventType.Sent,
HttpEventType.ResponseHeader,
HttpEventType.DownloadProgress,
HttpEventType.Response,
]);
const partial = events[1] as HttpHeaderResponse;
expect(partial.headers.get('Content-Type')).toEqual('text/plain');
expect(partial.headers.get('Test')).toEqual('Test header');
done();
});
factory.mock.mockResponseHeaders = 'Test: Test header\nContent-Type: text/plain\n';
factory.mock.mockDownloadProgressEvent(200);
factory.mock.mockFlush(200, 'OK', 'Done');
});
it('are unsubscribed along with the main request', () => {
const sub = backend.handle(TEST_POST.clone({reportProgress: true})).subscribe();
expect(factory.mock.listeners.progress).not.toBeUndefined();
sub.unsubscribe();
expect(factory.mock.listeners.progress).toBeUndefined();
});
it('do not cause headers to be re-parsed on main response', (done: DoneFn) => {
backend.handle(TEST_POST.clone({reportProgress: true})).toArray().subscribe(events => {
events
.filter(
event => event.type === HttpEventType.Response ||
event.type === HttpEventType.ResponseHeader)
.map(event => event as HttpResponseBase)
.forEach(event => {
expect(event.status).toBe(203);
expect(event.headers.get('Test')).toEqual('This is a test');
});
done();
});
factory.mock.mockResponseHeaders = 'Test: This is a test\n';
factory.mock.status = 203;
factory.mock.mockDownloadProgressEvent(100, 300);
factory.mock.mockResponseHeaders = 'Test: should never be read\n';
factory.mock.mockFlush(203, 'OK', 'Testing 1 2 3');
});
});
describe('gets response URL', () => {
it('from XHR.responsesURL', (done: DoneFn) => {
backend.handle(TEST_POST).toArray().subscribe(events => {
expect(events.length).toBe(2);
expect(events[1].type).toBe(HttpEventType.Response);
const response = events[1] as HttpResponse<string>;
expect(response.url).toBe('/response/url');
done();
});
factory.mock.responseURL = '/response/url';
factory.mock.mockFlush(200, 'OK', 'Test');
});
it('from X-Request-URL header if XHR.responseURL is not present', (done: DoneFn) => {
backend.handle(TEST_POST).toArray().subscribe(events => {
expect(events.length).toBe(2);
expect(events[1].type).toBe(HttpEventType.Response);
const response = events[1] as HttpResponse<string>;
expect(response.url).toBe('/response/url');
done();
});
factory.mock.mockResponseHeaders = 'X-Request-URL: /response/url\n';
factory.mock.mockFlush(200, 'OK', 'Test');
});
it('falls back on Request.url if neither are available', (done: DoneFn) => {
backend.handle(TEST_POST).toArray().subscribe(events => {
expect(events.length).toBe(2);
expect(events[1].type).toBe(HttpEventType.Response);
const response = events[1] as HttpResponse<string>;
expect(response.url).toBe('/test');
done();
});
factory.mock.mockFlush(200, 'OK', 'Test');
})
});
describe('corrects for quirks', () => {
it('by normalizing 1223 status to 204', (done: DoneFn) => {
backend.handle(TEST_POST).toArray().subscribe(events => {
expect(events.length).toBe(2);
expect(events[1].type).toBe(HttpEventType.Response);
const response = events[1] as HttpResponse<string>;
expect(response.status).toBe(204);
done();
});
factory.mock.mockFlush(1223, 'IE Special Status', 'Test');
});
it('by normalizing 0 status to 200 if a body is present', (done: DoneFn) => {
backend.handle(TEST_POST).toArray().subscribe(events => {
expect(events.length).toBe(2);
expect(events[1].type).toBe(HttpEventType.Response);
const response = events[1] as HttpResponse<string>;
expect(response.status).toBe(200);
done();
});
factory.mock.mockFlush(0, 'CORS 0 status', 'Test');
});
it('by leaving 0 status as 0 if a body is not present', (done: DoneFn) => {
backend.handle(TEST_POST).toArray().subscribe(undefined, (error: HttpErrorResponse) => {
expect(error.status).toBe(0);
done();
});
factory.mock.mockFlush(0, 'CORS 0 status', null);
});
});
});
}

View File

@ -0,0 +1,9 @@
/**
* @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
*/
export * from './public_api';

View File

@ -0,0 +1,7 @@
{
"name": "@angular/common/http/testing",
"typings": "../testing.d.ts",
"main": "../../bundles/common-http-testing.umd.js",
"module": "../../@angular/common/http/testing.es5.js",
"es2015": "../../@angular/common/http/testing.js"
}

View File

@ -0,0 +1,11 @@
/**
* @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
*/
export {HttpTestingController, RequestMatch} from './src/api';
export {HttpClientTestingModule} from './src/module';
export {TestRequest} from './src/request';

View File

@ -0,0 +1,29 @@
/**
* @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 resolve from 'rollup-plugin-node-resolve';
const globals = {
'@angular/core': 'ng.core',
'@angular/platform-browser': 'ng.platformBrowser',
'@angular/common/http': 'ng.common.http',
'rxjs/Observable': 'Rx',
'rxjs/ReplaySubject': 'Rx',
'rxjs/Subject': 'Rx',
};
export default {
entry: '../../../../dist/packages-dist/common/@angular/common/http/testing.es5.js',
dest: '../../../../dist/packages-dist/common/bundles/common-http-testing.umd.js',
format: 'umd',
exports: 'named',
moduleName: 'ng.common.http.testing',
plugins: [resolve()],
external: Object.keys(globals),
globals: globals
};

View File

@ -0,0 +1,49 @@
/**
* @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 {HttpRequest} from '@angular/common/http';
import {TestRequest} from './request';
/**
* Defines a matcher for requests based on URL, method, or both.
*
* @experimental
*/
export interface RequestMatch {
method?: string;
url?: string;
}
/**
* Controller to be injected into tests, that allows for mocking and flushing
* of requests.
*
* @experimental
*/
export abstract class HttpTestingController {
/**
* Search for requests that match the given parameter, without any expectations.
*/
abstract match(match: string|RequestMatch|((req: HttpRequest<any>) => boolean)): TestRequest[];
// Expect that exactly one request matches the given parameter.
abstract expectOne(url: string): TestRequest;
abstract expectOne(params: RequestMatch): TestRequest;
abstract expectOne(matchFn: ((req: HttpRequest<any>) => boolean)): TestRequest;
abstract expectOne(match: string|RequestMatch|((req: HttpRequest<any>) => boolean)): TestRequest;
// Assert that no requests match the given parameter.
abstract expectNone(url: string): void;
abstract expectNone(params: RequestMatch): void;
abstract expectNone(matchFn: ((req: HttpRequest<any>) => boolean)): void;
abstract expectNone(match: string|RequestMatch|((req: HttpRequest<any>) => boolean)): void;
// Validate that all requests which were issued were flushed.
abstract verify(opts?: {ignoreCancelled?: boolean}): void;
}

View File

@ -0,0 +1,124 @@
/**
* @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 {HttpBackend, HttpEvent, HttpEventType, HttpRequest} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Observer} from 'rxjs/Observer';
import {startWith} from 'rxjs/operator/startWith';
import {HttpTestingController, RequestMatch} from './api';
import {TestRequest} from './request';
/**
* A testing backend for `HttpClient` which both acts as an `HttpBackend`
* and as the `HttpTestingController`.
*
* `HttpClientTestingBackend` works by keeping a list of all open requests.
* As requests come in, they're added to the list. Users can assert that specific
* requests were made and then flush them. In the end, a verify() method asserts
* that no unexpected requests were made.
*
* @experimental
*/
@Injectable()
export class HttpClientTestingBackend implements HttpBackend, HttpTestingController {
/**
* List of pending requests which have not yet been expected.
*/
private open: TestRequest[] = [];
/**
* Handle an incoming request by queueing it in the list of open requests.
*/
handle(req: HttpRequest<any>): Observable<HttpEvent<any>> {
return new Observable((observer: Observer<HttpEvent<any>>) => {
const testReq = new TestRequest(req, observer);
this.open.push(testReq);
observer.next({type: HttpEventType.Sent});
return () => { testReq._cancelled = true; };
});
}
/**
* Helper function to search for requests in the list of open requests.
*/
private _match(match: string|RequestMatch|((req: HttpRequest<any>) => boolean)): TestRequest[] {
if (typeof match === 'string') {
return this.open.filter(testReq => testReq.request.url === match);
} else if (typeof match === 'function') {
return this.open.filter(testReq => match(testReq.request));
} else {
return this.open.filter(
testReq => (!match.method || testReq.request.method === match.method.toUpperCase()) &&
(!match.url || testReq.request.url === match.url));
}
}
/**
* Search for requests in the list of open requests, and return all that match
* without asserting anything about the number of matches.
*/
match(match: string|RequestMatch|((req: HttpRequest<any>) => boolean)): TestRequest[] {
const results = this._match(match);
results.forEach(result => {
const index = this.open.indexOf(result);
if (index !== -1) {
this.open.splice(index, 1);
}
});
return results;
}
/**
* Expect that a single outstanding request matches the given matcher, and return
* it.
*
* Requests returned through this API will no longer be in the list of open requests,
* and thus will not match twice.
*/
expectOne(match: string|RequestMatch|((req: HttpRequest<any>) => boolean)): TestRequest {
const matches = this.match(match);
if (matches.length > 1) {
throw new Error(`Expected one matching request, found ${matches.length} requests.`);
}
if (matches.length === 0) {
throw new Error(`Expected one matching request, found none.`);
}
return matches[0];
}
/**
* Expect that no outstanding requests match the given matcher, and throw an error
* if any do.
*/
expectNone(match: string|RequestMatch|((req: HttpRequest<any>) => boolean)): void {
const matches = this.match(match);
if (matches.length > 0) {
throw new Error(`Expected zero matching requests, found ${matches.length}.`);
}
}
/**
* Validate that there are no outstanding requests.
*/
verify(opts: {ignoreCancelled?: boolean} = {}): void {
let open = this.open;
// It's possible that some requests may be cancelled, and this is expected.
// The user can ask to ignore open requests which have been cancelled.
if (opts.ignoreCancelled) {
open = open.filter(testReq => !testReq.cancelled);
}
if (open.length > 0) {
// Show the URLs of open requests in the error, for convenience.
const urls = open.map(testReq => testReq.request.url.split('?')[0]).join(', ');
throw new Error(`Expected no open requests, found ${open.length}: ${urls}`);
}
}
}

View File

@ -0,0 +1,34 @@
/**
* @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 {HttpBackend, HttpClientModule} from '@angular/common/http';
import {NgModule} from '@angular/core';
import {HttpTestingController} from './api';
import {HttpClientTestingBackend} from './backend';
/**
* Configures `HttpClientTestingBackend` as the `HttpBackend` used by `HttpClient`.
*
* Inject `HttpTestingController` to expect and flush requests in your tests.
*
* @experimental
*/
@NgModule({
imports: [
HttpClientModule,
],
providers: [
HttpClientTestingBackend,
{provide: HttpBackend, useExisting: HttpClientTestingBackend},
{provide: HttpTestingController, useExisting: HttpClientTestingBackend},
],
})
export class HttpClientTestingModule {
}

View File

@ -0,0 +1,200 @@
/**
* @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 {HttpErrorResponse, HttpEvent, HttpEventType, HttpHeaders, HttpRequest, HttpResponse} from '@angular/common/http';
import {Observer} from 'rxjs/Observer';
/**
* A mock requests that was received and is ready to be answered.
*
* This interface allows access to the underlying `HttpRequest`, and allows
* responding with `HttpEvent`s or `HttpErrorResponse`s.
*
* @experimental
*/
export class TestRequest {
/**
* Whether the request was cancelled after it was sent.
*/
get cancelled(): boolean { return this._cancelled; }
/**
* @internal set by `HttpClientTestingBackend`
*/
_cancelled = false;
constructor(public request: HttpRequest<any>, private observer: Observer<HttpEvent<any>>) {}
flush(body: ArrayBuffer|Blob|string|number|Object|(string|number|Object|null)[]|null, opts: {
headers?: HttpHeaders | {[name: string]: string | string[]},
status?: number,
statusText?: string,
} = {}): void {
if (this.cancelled) {
throw new Error(`Cannot flush a cancelled request.`);
}
const url = this.request.url;
const headers =
(opts.headers instanceof HttpHeaders) ? opts.headers : new HttpHeaders(opts.headers);
body = _maybeConvertBody(this.request.responseType, body);
let statusText: string|undefined = opts.statusText;
let status: number = opts.status !== undefined ? opts.status : 200;
if (opts.status === undefined) {
if (body === null) {
status = 204;
statusText = statusText || 'No Content';
} else {
statusText = statusText || 'OK';
}
}
if (statusText === undefined) {
throw new Error('statusText is required when setting a custom status.');
}
const res = {body, headers, status, statusText, url};
if (status >= 200 && status < 300) {
this.observer.next(new HttpResponse<any>(res));
this.observer.complete();
} else {
this.observer.error(new HttpErrorResponse(res));
}
}
error(error: ErrorEvent, opts: {
headers?: HttpHeaders | {[name: string]: string | string[]},
status?: number,
statusText?: string,
} = {}): void {
if (this.cancelled) {
throw new Error(`Cannot return an error for a cancelled request.`);
}
if (opts.status && opts.status >= 200 && opts.status < 300) {
throw new Error(`error() called with a successful status.`);
}
const headers =
(opts.headers instanceof HttpHeaders) ? opts.headers : new HttpHeaders(opts.headers);
this.observer.error(new HttpErrorResponse({
error,
headers,
status: opts.status || 0,
statusText: opts.statusText || '',
url: this.request.url,
}));
}
event(event: HttpEvent<any>): void {
if (this.cancelled) {
throw new Error(`Cannot send events to a cancelled request.`);
}
this.observer.next(event);
}
}
/**
* Helper function to convert a response body to an ArrayBuffer.
*/
function _toArrayBufferBody(
body: ArrayBuffer | Blob | string | number | Object |
(string | number | Object | null)[]): ArrayBuffer {
if (typeof ArrayBuffer === 'undefined') {
throw new Error('ArrayBuffer responses are not supported on this platform.');
}
if (body instanceof ArrayBuffer) {
return body;
}
throw new Error('Automatic conversion to ArrayBuffer is not supported for response type.');
}
/**
* Helper function to convert a response body to a Blob.
*/
function _toBlob(
body: ArrayBuffer | Blob | string | number | Object |
(string | number | Object | null)[]): Blob {
if (typeof Blob === 'undefined') {
throw new Error('Blob responses are not supported on this platform.');
}
if (body instanceof Blob) {
return body;
}
if (ArrayBuffer && body instanceof ArrayBuffer) {
return new Blob([body]);
}
throw new Error('Automatic conversion to Blob is not supported for response type.');
}
/**
* Helper function to convert a response body to JSON data.
*/
function _toJsonBody(
body: ArrayBuffer | Blob | string | number | Object | (string | number | Object | null)[],
format: string = 'JSON'): Object|string|number|(Object | string | number)[] {
if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer) {
throw new Error(`Automatic conversion to ${format} is not supported for ArrayBuffers.`);
}
if (typeof Blob !== 'undefined' && body instanceof Blob) {
throw new Error(`Automatic conversion to ${format} is not supported for Blobs.`);
}
if (typeof body === 'string' || typeof body === 'number' || typeof body === 'object' ||
Array.isArray(body)) {
return body;
}
throw new Error(`Automatic conversion to ${format} is not supported for response type.`);
}
/**
* Helper function to convert a response body to a string.
*/
function _toTextBody(
body: ArrayBuffer | Blob | string | number | Object |
(string | number | Object | null)[]): string {
if (typeof body === 'string') {
return body;
}
if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer) {
throw new Error('Automatic conversion to text is not supported for ArrayBuffers.');
}
if (typeof Blob !== 'undefined' && body instanceof Blob) {
throw new Error('Automatic conversion to text is not supported for Blobs.');
}
return JSON.stringify(_toJsonBody(body, 'text'));
}
/**
* Convert a response body to the requested type.
*/
function _maybeConvertBody(
responseType: string, body: ArrayBuffer | Blob | string | number | Object |
(string | number | Object | null)[] | null): ArrayBuffer|Blob|string|number|Object|
(string | number | Object | null)[]|null {
switch (responseType) {
case 'arraybuffer':
if (body === null) {
return null;
}
return _toArrayBufferBody(body);
case 'blob':
if (body === null) {
return null;
}
return _toBlob(body);
case 'json':
if (body === null) {
return 'null';
}
return _toJsonBody(body);
case 'text':
if (body === null) {
return null;
}
return _toTextBody(body);
default:
throw new Error(`Unsupported responseType: ${responseType}`);
}
}

View File

@ -0,0 +1,32 @@
{
"compilerOptions": {
"baseUrl": ".",
"declaration": true,
"stripInternal": true,
"experimentalDecorators": true,
"module": "es2015",
"moduleResolution": "node",
"outDir": "../../../../dist/packages/common/http/testing",
"paths": {
"@angular/core": ["../../../../dist/packages/core"],
"@angular/common": ["../../../../dist/packages/common"],
"@angular/common/http": ["../../../../dist/packages/common/http"],
"@angular/platform-browser": ["../../../../dist/packages/platform-browser"]
},
"rootDir": ".",
"sourceMap": true,
"inlineSources": true,
"target": "es2015",
"skipLibCheck": true,
"lib": ["es2015", "dom"]
},
"files": [
"public_api.ts"
],
"angularCompilerOptions": {
"annotateForClosureCompiler": true,
"strictMetadataEmit": true,
"flatModuleOutFile": "index.js",
"flatModuleId": "@angular/common/http/testing"
}
}

View File

@ -0,0 +1,30 @@
{
"compilerOptions": {
"baseUrl": ".",
"declaration": true,
"stripInternal": true,
"experimentalDecorators": true,
"module": "es2015",
"moduleResolution": "node",
"outDir": "../../../dist/packages/common/http",
"paths": {
"@angular/common": ["../../../dist/packages/common"],
"@angular/core": ["../../../dist/packages/core"]
},
"rootDir": ".",
"sourceMap": true,
"inlineSources": true,
"target": "es2015",
"skipLibCheck": true,
"lib": ["es2015", "dom"]
},
"files": [
"public_api.ts"
],
"angularCompilerOptions": {
"annotateForClosureCompiler": true,
"strictMetadataEmit": true,
"flatModuleOutFile": "index.js",
"flatModuleId": "@angular/common/http"
}
}

View File

@ -6,9 +6,9 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {DOCUMENT as commonDOCUMENT} from '@angular/common';
import {InjectionToken} from '@angular/core'; import {InjectionToken} from '@angular/core';
import {DOCUMENT as commonDOCUMENT} from '@angular/common';
/** /**
* A DI Token representing the main rendering context. In a browser this is the DOM Document. * A DI Token representing the main rendering context. In a browser this is the DOM Document.
@ -16,6 +16,6 @@ import {DOCUMENT as commonDOCUMENT} from '@angular/common';
* Note: Document might not be available in the Application Context when Application and Rendering * Note: Document might not be available in the Application Context when Application and Rendering
* Contexts are not the same (e.g. when running the application into a Web Worker). * Contexts are not the same (e.g. when running the application into a Web Worker).
* *
* @deprecated, import from `@angular/common` instead. * @deprecated import from `@angular/common` instead.
*/ */
export const DOCUMENT = commonDOCUMENT; export const DOCUMENT = commonDOCUMENT;

View File

@ -8,9 +8,11 @@
const xhr2: any = require('xhr2'); const xhr2: any = require('xhr2');
import {Injectable, Provider} from '@angular/core'; import {Injectable, Optional, Provider} from '@angular/core';
import {BrowserXhr, Connection, ConnectionBackend, Http, ReadyState, Request, RequestOptions, Response, XHRBackend, XSRFStrategy} from '@angular/http'; import {BrowserXhr, Connection, ConnectionBackend, Http, ReadyState, Request, RequestOptions, Response, XHRBackend, XSRFStrategy} from '@angular/http';
import {HttpClient, HttpRequest, HttpHandler, HttpInterceptor, HttpResponse, HTTP_INTERCEPTORS, HttpBackend, XhrFactory, ɵinterceptingHandler as interceptingHandler} from '@angular/common/http';
import {Observable} from 'rxjs/Observable'; import {Observable} from 'rxjs/Observable';
import {Observer} from 'rxjs/Observer'; import {Observer} from 'rxjs/Observer';
import {Subscription} from 'rxjs/Subscription'; import {Subscription} from 'rxjs/Subscription';
@ -33,13 +35,9 @@ export class ServerXsrfStrategy implements XSRFStrategy {
configureRequest(req: Request): void {} configureRequest(req: Request): void {}
} }
export class ZoneMacroTaskConnection implements Connection { export abstract class ZoneMacroTaskWrapper<S, R> {
response: Observable<Response>; wrap(request: S): Observable<R> {
lastConnection: Connection; return new Observable((observer: Observer<R>) => {
constructor(public request: Request, backend: XHRBackend) {
validateRequestUrl(request.url);
this.response = new Observable((observer: Observer<Response>) => {
let task: Task = null !; let task: Task = null !;
let scheduled: boolean = false; let scheduled: boolean = false;
let sub: Subscription|null = null; let sub: Subscription|null = null;
@ -50,13 +48,13 @@ export class ZoneMacroTaskConnection implements Connection {
task = _task; task = _task;
scheduled = true; scheduled = true;
this.lastConnection = backend.createConnection(request); const delegate = this.delegate(request);
sub = (this.lastConnection.response as Observable<Response>) sub = delegate.subscribe(
.subscribe(
res => savedResult = res, res => savedResult = res,
err => { err => {
if (!scheduled) { if (!scheduled) {
throw new Error('invoke twice'); throw new Error(
'An http observable was completed twice. This shouldn\'t happen, please file a bug.');
} }
savedError = err; savedError = err;
scheduled = false; scheduled = false;
@ -64,7 +62,8 @@ export class ZoneMacroTaskConnection implements Connection {
}, },
() => { () => {
if (!scheduled) { if (!scheduled) {
throw new Error('invoke twice'); throw new Error(
'An http observable was completed twice. This shouldn\'t happen, please file a bug.');
} }
scheduled = false; scheduled = false;
task.invoke(); task.invoke();
@ -91,11 +90,11 @@ export class ZoneMacroTaskConnection implements Connection {
} }
}; };
// MockBackend is currently synchronous, which means that if scheduleTask is by // MockBackend for Http is synchronous, which means that if scheduleTask is by
// scheduleMacroTask, the request will hit MockBackend and the response will be // scheduleMacroTask, the request will hit MockBackend and the response will be
// sent, causing task.invoke() to be called. // sent, causing task.invoke() to be called.
const _task = Zone.current.scheduleMacroTask( const _task = Zone.current.scheduleMacroTask(
'ZoneMacroTaskConnection.subscribe', onComplete, {}, () => null, cancelTask); 'ZoneMacroTaskWrapper.subscribe', onComplete, {}, () => null, cancelTask);
scheduleTask(_task); scheduleTask(_task);
return () => { return () => {
@ -111,6 +110,25 @@ export class ZoneMacroTaskConnection implements Connection {
}); });
} }
protected abstract delegate(request: S): Observable<R>;
}
export class ZoneMacroTaskConnection extends ZoneMacroTaskWrapper<Request, Response> implements
Connection {
response: Observable<Response>;
lastConnection: Connection;
constructor(public request: Request, private backend: XHRBackend) {
super();
validateRequestUrl(request.url);
this.response = this.wrap(request);
}
delegate(request: Request): Observable<Response> {
this.lastConnection = this.backend.createConnection(request);
return this.lastConnection.response as Observable<Response>;
}
get readyState(): ReadyState { get readyState(): ReadyState {
return !!this.lastConnection ? this.lastConnection.readyState : ReadyState.Unsent; return !!this.lastConnection ? this.lastConnection.readyState : ReadyState.Unsent;
} }
@ -124,13 +142,34 @@ export class ZoneMacroTaskBackend implements ConnectionBackend {
} }
} }
export class ZoneClientBackend extends
ZoneMacroTaskWrapper<HttpRequest<any>, HttpResponse<any>> implements HttpBackend {
constructor(private backend: HttpBackend) { super(); }
handle(request: HttpRequest<any>): Observable<HttpResponse<any>> { return this.wrap(request); }
protected delegate(request: HttpRequest<any>): Observable<HttpResponse<any>> {
return this.backend.handle(request);
}
}
export function httpFactory(xhrBackend: XHRBackend, options: RequestOptions) { export function httpFactory(xhrBackend: XHRBackend, options: RequestOptions) {
const macroBackend = new ZoneMacroTaskBackend(xhrBackend); const macroBackend = new ZoneMacroTaskBackend(xhrBackend);
return new Http(macroBackend, options); return new Http(macroBackend, options);
} }
export function zoneWrappedInterceptingHandler(
backend: HttpBackend, interceptors: HttpInterceptor[] | null) {
const realBackend: HttpBackend = interceptingHandler(backend, interceptors);
return new ZoneClientBackend(realBackend);
}
export const SERVER_HTTP_PROVIDERS: Provider[] = [ export const SERVER_HTTP_PROVIDERS: Provider[] = [
{provide: Http, useFactory: httpFactory, deps: [XHRBackend, RequestOptions]}, {provide: Http, useFactory: httpFactory, deps: [XHRBackend, RequestOptions]},
{provide: BrowserXhr, useClass: ServerXhr}, {provide: BrowserXhr, useClass: ServerXhr}, {provide: XSRFStrategy, useClass: ServerXsrfStrategy},
{provide: XSRFStrategy, useClass: ServerXsrfStrategy}, {
provide: HttpHandler,
useFactory: zoneWrappedInterceptingHandler,
deps: [HttpBackend, [new Optional(), HTTP_INTERCEPTORS]]
}
]; ];

View File

@ -8,6 +8,7 @@
import {ɵAnimationEngine} from '@angular/animations/browser'; import {ɵAnimationEngine} from '@angular/animations/browser';
import {PlatformLocation, ɵPLATFORM_SERVER_ID as PLATFORM_SERVER_ID} from '@angular/common'; import {PlatformLocation, ɵPLATFORM_SERVER_ID as PLATFORM_SERVER_ID} from '@angular/common';
import {HttpClientModule} from '@angular/common/http';
import {platformCoreDynamic} from '@angular/compiler'; import {platformCoreDynamic} from '@angular/compiler';
import {Injectable, InjectionToken, Injector, NgModule, NgZone, PLATFORM_ID, PLATFORM_INITIALIZER, PlatformRef, Provider, RendererFactory2, RootRenderer, Testability, createPlatformFactory, isDevMode, platformCore, ɵALLOW_MULTIPLE_PLATFORMS as ALLOW_MULTIPLE_PLATFORMS} from '@angular/core'; import {Injectable, InjectionToken, Injector, NgModule, NgZone, PLATFORM_ID, PLATFORM_INITIALIZER, PlatformRef, Provider, RendererFactory2, RootRenderer, Testability, createPlatformFactory, isDevMode, platformCore, ɵALLOW_MULTIPLE_PLATFORMS as ALLOW_MULTIPLE_PLATFORMS} from '@angular/core';
import {HttpModule} from '@angular/http'; import {HttpModule} from '@angular/http';
@ -62,7 +63,7 @@ export const SERVER_RENDER_PROVIDERS: Provider[] = [
*/ */
@NgModule({ @NgModule({
exports: [BrowserModule], exports: [BrowserModule],
imports: [HttpModule, NoopAnimationsModule], imports: [HttpModule, HttpClientModule, NoopAnimationsModule],
providers: [ providers: [
SERVER_RENDER_PROVIDERS, SERVER_RENDER_PROVIDERS,
SERVER_HTTP_PROVIDERS, SERVER_HTTP_PROVIDERS,

View File

@ -12,6 +12,7 @@
"@angular/animations/browser": ["../../dist/packages/animations/browser"], "@angular/animations/browser": ["../../dist/packages/animations/browser"],
"@angular/core": ["../../dist/packages/core"], "@angular/core": ["../../dist/packages/core"],
"@angular/common": ["../../dist/packages/common"], "@angular/common": ["../../dist/packages/common"],
"@angular/common/http": ["../../dist/packages/common/http"],
"@angular/compiler": ["../../dist/packages/compiler"], "@angular/compiler": ["../../dist/packages/compiler"],
"@angular/http": ["../../dist/packages/http"], "@angular/http": ["../../dist/packages/http"],
"@angular/platform-browser": ["../../dist/packages/platform-browser"], "@angular/platform-browser": ["../../dist/packages/platform-browser"],

View File

@ -40,6 +40,8 @@ System.config({
'@angular/compiler/testing': {main: 'index.js', defaultExtension: 'js'}, '@angular/compiler/testing': {main: 'index.js', defaultExtension: 'js'},
'@angular/compiler': {main: 'index.js', defaultExtension: 'js'}, '@angular/compiler': {main: 'index.js', defaultExtension: 'js'},
'@angular/common/testing': {main: 'index.js', defaultExtension: 'js'}, '@angular/common/testing': {main: 'index.js', defaultExtension: 'js'},
'@angular/common/http/testing': {main: 'index.js', defaultExtension: 'js'},
'@angular/common/http': {main: 'index.js', defaultExtension: 'js'},
'@angular/common': {main: 'index.js', defaultExtension: 'js'}, '@angular/common': {main: 'index.js', defaultExtension: 'js'},
'@angular/forms': {main: 'index.js', defaultExtension: 'js'}, '@angular/forms': {main: 'index.js', defaultExtension: 'js'},
// remove after all tests imports are fixed // remove after all tests imports are fixed

View File

@ -1,6 +1,7 @@
const entrypoints = [ const entrypoints = [
'dist/packages-dist/core/core.d.ts', 'dist/packages-dist/core/testing.d.ts', 'dist/packages-dist/core/core.d.ts', 'dist/packages-dist/core/testing.d.ts',
'dist/packages-dist/common/common.d.ts', 'dist/packages-dist/common/testing.d.ts', 'dist/packages-dist/common/common.d.ts', 'dist/packages-dist/common/testing.d.ts',
'dist/packages-dist/common/http.d.ts', 'dist/packages-dist/common/http/testing.d.ts',
// The API surface of the compiler is currently unstable - all of the important APIs are exposed // The API surface of the compiler is currently unstable - all of the important APIs are exposed
// via @angular/core, @angular/platform-browser or @angular/platform-browser-dynamic instead. // via @angular/core, @angular/platform-browser or @angular/platform-browser-dynamic instead.
//'dist/packages-dist/compiler/index.d.ts', //'dist/packages-dist/compiler/index.d.ts',

View File

@ -33,6 +33,9 @@ export declare class DecimalPipe implements PipeTransform {
transform(value: any, digits?: string): string | null; transform(value: any, digits?: string): string | null;
} }
/** @stable */
export declare const DOCUMENT: InjectionToken<Document>;
/** @stable */ /** @stable */
export declare class HashLocationStrategy extends LocationStrategy { export declare class HashLocationStrategy extends LocationStrategy {
constructor(_platformLocation: PlatformLocation, _baseHref?: string); constructor(_platformLocation: PlatformLocation, _baseHref?: string);

991
tools/public_api_guard/common/http.d.ts vendored Normal file
View File

@ -0,0 +1,991 @@
/** @experimental */
export declare const HTTP_INTERCEPTORS: InjectionToken<HttpInterceptor[]>;
/** @experimental */
export declare abstract class HttpBackend implements HttpHandler {
abstract handle(req: HttpRequest<any>): Observable<HttpEvent<any>>;
}
/** @experimental */
export declare class HttpClient {
constructor(handler: HttpHandler);
delete<T>(url: string, options?: {
headers?: HttpHeaders;
observe?: 'body';
responseType?: 'json';
withCredentials?: boolean;
}): Observable<T>;
delete(url: string, options?: {
headers?: HttpHeaders;
observe?: 'body';
responseType?: 'json';
withCredentials?: boolean;
}): Observable<Object>;
delete<T>(url: string, options: {
headers?: HttpHeaders;
observe: 'response';
responseType?: 'json';
withCredentials?: boolean;
}): Observable<HttpResponse<T>>;
delete(url: string, options: {
headers?: HttpHeaders;
observe: 'response';
responseType?: 'json';
withCredentials?: boolean;
}): Observable<HttpResponse<Object>>;
delete(url: string, options: {
headers?: HttpHeaders;
observe: 'response';
responseType: 'text';
withCredentials?: boolean;
}): Observable<HttpResponse<string>>;
delete(url: string, options: {
headers?: HttpHeaders;
observe: 'response';
responseType: 'blob';
withCredentials?: boolean;
}): Observable<HttpResponse<Blob>>;
delete(url: string, options: {
headers?: HttpHeaders;
observe: 'response';
responseType: 'arraybuffer';
withCredentials?: boolean;
}): Observable<HttpResponse<ArrayBuffer>>;
delete<T>(url: string, options: {
headers?: HttpHeaders;
observe: 'events';
responseType?: 'json';
withCredentials?: boolean;
}): Observable<HttpEvent<T>>;
delete(url: string, options: {
headers?: HttpHeaders;
observe: 'events';
responseType?: 'json';
withCredentials?: boolean;
}): Observable<HttpEvent<Object>>;
delete(url: string, options: {
headers?: HttpHeaders;
observe: 'events';
responseType: 'text';
withCredentials?: boolean;
}): Observable<HttpEvent<string>>;
delete(url: string, options: {
headers?: HttpHeaders;
observe: 'events';
responseType: 'blob';
withCredentials?: boolean;
}): Observable<HttpEvent<Blob>>;
delete(url: string, options: {
headers?: HttpHeaders;
observe: 'events';
responseType: 'arraybuffer';
withCredentials?: boolean;
}): Observable<HttpEvent<ArrayBuffer>>;
delete(url: string, options: {
headers?: HttpHeaders;
observe?: 'body';
responseType: 'text';
withCredentials?: boolean;
}): Observable<string>;
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>;
get<T>(url: string, options: {
headers?: HttpHeaders;
observe: 'events';
responseType?: 'json';
withCredentials?: boolean;
}): Observable<HttpEvent<T>>;
get(url: string, options: {
headers?: HttpHeaders;
observe?: 'body';
responseType: 'text';
withCredentials?: boolean;
}): Observable<string>;
get(url: string, options: {
headers?: HttpHeaders;
observe?: 'body';
responseType: 'blob';
withCredentials?: boolean;
}): Observable<Blob>;
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(url: string, options: {
headers?: HttpHeaders;
observe?: 'body';
responseType: 'arraybuffer';
withCredentials?: boolean;
}): Observable<ArrayBuffer>;
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>;
head(url: string, options: {
headers?: HttpHeaders;
observe: 'events';
responseType: 'arraybuffer';
withCredentials?: boolean;
}): Observable<HttpEvent<ArrayBuffer>>;
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>;
head(url: string, options: {
headers?: HttpHeaders;
observe?: 'body';
responseType: 'text';
withCredentials?: boolean;
}): Observable<string>;
head(url: string, options: {
headers?: HttpHeaders;
observe: 'events';
responseType: 'blob';
withCredentials?: boolean;
}): Observable<HttpEvent<Blob>>;
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>;
jsonp(url: string): Observable<any>;
jsonp<T>(url: string): Observable<T>;
options(url: string, options: {
headers?: HttpHeaders;
observe: 'response';
responseType: 'arraybuffer';
withCredentials?: boolean;
}): Observable<HttpResponse<ArrayBuffer>>;
options(url: string, options: {
headers?: HttpHeaders;
observe?: 'body';
responseType: 'arraybuffer';
withCredentials?: boolean;
}): Observable<ArrayBuffer>;
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?: 'body';
responseType: 'blob';
withCredentials?: boolean;
}): Observable<Blob>;
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>;
patch(url: string, body: any | null, options: {
headers?: HttpHeaders;
observe: 'events';
responseType?: 'json';
withCredentials?: boolean;
}): Observable<HttpEvent<Object>>;
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<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>;
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?: 'body';
responseType: 'arraybuffer';
withCredentials?: boolean;
}): Observable<ArrayBuffer>;
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(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: '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>;
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: 'response';
responseType?: 'json';
withCredentials?: boolean;
}): Observable<HttpResponse<T>>;
put(url: string, body: any | null, options: {
headers?: HttpHeaders;
observe: 'response';
responseType?: 'json';
withCredentials?: boolean;
}): Observable<HttpResponse<Object>>;
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: 'blob';
withCredentials?: boolean;
}): Observable<HttpResponse<Blob>>;
put(url: string, body: any | null, options: {
headers?: HttpHeaders;
observe: 'response';
responseType: 'arraybuffer';
withCredentials?: boolean;
}): Observable<HttpResponse<ArrayBuffer>>;
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?: 'body';
responseType: 'arraybuffer';
withCredentials?: boolean;
}): Observable<ArrayBuffer>;
put(url: string, body: any | null, options: {
headers?: HttpHeaders;
observe: 'events';
responseType?: 'json';
withCredentials?: boolean;
}): Observable<HttpEvent<Object>>;
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: 'blob';
withCredentials?: boolean;
}): Observable<HttpEvent<Blob>>;
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?: 'body';
responseType: 'text';
withCredentials?: boolean;
}): Observable<string>;
put(url: string, body: any | null, options: {
headers?: HttpHeaders;
observe?: 'body';
responseType: 'blob';
withCredentials?: boolean;
}): Observable<Blob>;
put<T>(url: string, body: any | null, options?: {
headers?: HttpHeaders;
observe?: 'body';
responseType?: 'json';
withCredentials?: boolean;
}): Observable<T>;
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?: 'body';
responseType?: 'json';
withCredentials?: boolean;
}): Observable<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<R>(req: HttpRequest<any>): Observable<HttpEvent<R>>;
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(method: string, url: string, options?: {
body?: any;
headers?: HttpHeaders;
observe?: HttpObserve;
responseType?: 'arraybuffer' | 'blob' | 'json' | 'text';
withCredentials?: boolean;
}): Observable<any>;
}
/** @experimental */
export declare class HttpClientJsonpModule {
}
/** @experimental */
export declare class HttpClientModule {
}
/** @experimental */
export interface HttpDownloadProgressEvent extends HttpProgressEvent {
partialText?: string;
type: HttpEventType.DownloadProgress;
}
/** @experimental */
export declare class HttpErrorResponse extends HttpResponseBase implements Error {
readonly error: any | null;
readonly message: string;
readonly name: string;
readonly ok: boolean;
constructor(init: {
error?: any;
headers?: HttpHeaders;
status?: number;
statusText?: string;
url?: string;
});
}
/** @experimental */
export declare type HttpEvent<T> = HttpSentEvent | HttpHeaderResponse | HttpResponse<T> | HttpProgressEvent | HttpUserEvent<T>;
/** @experimental */
export declare enum HttpEventType {
Sent = 0,
UploadProgress = 1,
ResponseHeader = 2,
DownloadProgress = 3,
Response = 4,
User = 5,
}
/** @experimental */
export declare abstract class HttpHandler {
abstract handle(req: HttpRequest<any>): Observable<HttpEvent<any>>;
}
/** @experimental */
export declare class HttpHeaderResponse extends HttpResponseBase {
readonly type: HttpEventType.ResponseHeader;
constructor(init?: {
headers?: HttpHeaders;
status?: number;
statusText?: string;
url?: string;
});
clone(update?: {
headers?: HttpHeaders;
status?: number;
statusText?: string;
url?: string;
}): HttpHeaderResponse;
}
/** @experimental */
export declare class HttpHeaders {
constructor(headers?: string | {
[name: string]: string | string[];
});
append(name: string, value: string | string[]): HttpHeaders;
delete(name: string, value?: string | string[]): HttpHeaders;
get(name: string): string | null;
getAll(name: string): string[] | null;
has(name: string): boolean;
keys(): string[];
set(name: string, value: string | string[]): HttpHeaders;
}
/** @experimental */
export interface HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>;
}
/** @experimental */
export interface HttpProgressEvent {
loaded: number;
total?: number;
type: HttpEventType.DownloadProgress | HttpEventType.UploadProgress;
}
/** @experimental */
export declare class HttpRequest<T> {
readonly body: T | null;
readonly headers: HttpHeaders;
readonly method: string;
readonly reportProgress: boolean;
readonly responseType: 'arraybuffer' | 'blob' | 'json' | 'text';
url: string;
readonly withCredentials: boolean;
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;
});
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>;
detectContentTypeHeader(): string | null;
serializeBody(): ArrayBuffer | Blob | FormData | string | null;
}
/** @experimental */
export declare class HttpResponse<T> extends HttpResponseBase {
readonly body: T | null;
readonly type: HttpEventType.Response;
constructor(init?: {
body?: T | null;
headers?: HttpHeaders;
status?: number;
statusText?: string;
url?: string;
});
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>;
}
/** @experimental */
export declare abstract class HttpResponseBase {
readonly headers: HttpHeaders;
readonly ok: boolean;
readonly status: number;
readonly statusText: string;
readonly type: HttpEventType.Response | HttpEventType.ResponseHeader;
readonly url: string | null;
constructor(init: {
headers?: HttpHeaders;
status?: number;
statusText?: string;
url?: string;
}, defaultStatus?: number, defaultStatusText?: string);
}
/** @experimental */
export interface HttpSentEvent {
type: HttpEventType.Sent;
}
/** @experimental */
export declare class HttpStandardUrlParameterCodec implements HttpUrlParameterCodec {
decodeKey(k: string): string;
decodeValue(v: string): string;
encodeKey(k: string): string;
encodeValue(v: string): string;
}
/** @experimental */
export declare class HttpUrlEncodedBody {
constructor(options?: {
fromString?: string;
encoder?: HttpUrlParameterCodec;
});
append(param: string, value: string): HttpUrlEncodedBody;
delete(param: string, value?: string): HttpUrlEncodedBody;
get(param: string): string | null;
getAll(param: string): string[] | null;
has(param: string): boolean;
params(): string[];
set(param: string, value: string): HttpUrlEncodedBody;
toString(): string;
}
/** @experimental */
export interface HttpUrlParameterCodec {
decodeKey(key: string): string;
decodeValue(value: string): string;
encodeKey(key: string): string;
encodeValue(value: string): string;
}
/** @experimental */
export interface HttpUserEvent<T> {
type: HttpEventType.User;
}
/** @experimental */
export declare class HttpXhrBackend implements HttpBackend {
constructor(xhrFactory: XhrFactory);
handle(req: HttpRequest<any>): Observable<HttpEvent<any>>;
}
/** @experimental */
export declare class JsonpClientBackend implements HttpBackend {
constructor(callbackMap: JsonpCallbackContext, document: any);
handle(req: HttpRequest<never>): Observable<HttpEvent<any>>;
}
/** @experimental */
export declare class JsonpInterceptor {
constructor(jsonp: JsonpClientBackend);
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>;
}
/** @experimental */
export declare abstract class XhrFactory {
abstract build(): XMLHttpRequest;
}

View File

@ -0,0 +1,47 @@
/** @experimental */
export declare class HttpClientTestingModule {
}
/** @experimental */
export declare abstract class HttpTestingController {
abstract expectNone(url: string): void;
abstract expectNone(params: RequestMatch): void;
abstract expectNone(matchFn: ((req: HttpRequest<any>) => boolean)): void;
abstract expectNone(match: string | RequestMatch | ((req: HttpRequest<any>) => boolean)): void;
abstract expectOne(url: string): TestRequest;
abstract expectOne(params: RequestMatch): TestRequest;
abstract expectOne(matchFn: ((req: HttpRequest<any>) => boolean)): TestRequest;
abstract expectOne(match: string | RequestMatch | ((req: HttpRequest<any>) => boolean)): TestRequest;
abstract match(match: string | RequestMatch | ((req: HttpRequest<any>) => boolean)): TestRequest[];
abstract verify(opts?: {
ignoreCancelled?: boolean;
}): void;
}
/** @experimental */
export interface RequestMatch {
method?: string;
url?: string;
}
/** @experimental */
export declare class TestRequest {
readonly cancelled: boolean;
request: HttpRequest<any>;
constructor(request: HttpRequest<any>, observer: Observer<HttpEvent<any>>);
error(error: ErrorEvent, opts?: {
headers?: HttpHeaders | {
[name: string]: string | string[];
};
status?: number;
statusText?: string;
}): void;
event(event: HttpEvent<any>): void;
flush(body: ArrayBuffer | Blob | string | number | Object | (string | number | Object | null)[] | null, opts?: {
headers?: HttpHeaders | {
[name: string]: string | string[];
};
status?: number;
statusText?: string;
}): void;
}

View File

@ -16,7 +16,7 @@ export declare class By {
/** @experimental */ /** @experimental */
export declare function disableDebugTools(): void; export declare function disableDebugTools(): void;
/** @stable */ /** @deprecated */
export declare const DOCUMENT: InjectionToken<Document>; export declare const DOCUMENT: InjectionToken<Document>;
/** @stable */ /** @stable */