@angular/http
Version:
Angular - the http service
1,292 lines (1,279 loc) • 90.6 kB
JavaScript
/**
* @license Angular v2.0.1
* (c) 2010-2016 Google, Inc. https://angular.io/
* License: MIT
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('rxjs/Observable'), require('@angular/platform-browser')) :
typeof define === 'function' && define.amd ? define(['exports', '@angular/core', 'rxjs/Observable', '@angular/platform-browser'], factory) :
(factory((global.ng = global.ng || {}, global.ng.http = global.ng.http || {}),global.ng.core,global.Rx,global.ng.platformBrowser));
}(this, function (exports,_angular_core,rxjs_Observable,_angular_platformBrowser) { 'use strict';
/**
* A backend for http that uses the `XMLHttpRequest` browser API.
*
* Take care not to evaluate this in non-browser contexts.
*
* @experimental
*/
var BrowserXhr = (function () {
function BrowserXhr() {
}
BrowserXhr.prototype.build = function () { return (new XMLHttpRequest()); };
BrowserXhr.decorators = [
{ type: _angular_core.Injectable },
];
/** @nocollapse */
BrowserXhr.ctorParameters = [];
return BrowserXhr;
}());
/**
* @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
*/
var globalScope;
if (typeof window === 'undefined') {
if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {
// TODO: Replace any with WorkerGlobalScope from lib.webworker.d.ts #3492
globalScope = self;
}
else {
globalScope = global;
}
}
else {
globalScope = window;
}
// Need to declare a new variable for global here since TypeScript
// exports the original value of the symbol.
var global$1 = globalScope;
// TODO: remove calls to assert in production environment
// Note: Can't just export this and import in in other files
// as `assert` is a reserved keyword in Dart
global$1.assert = function assert(condition) {
// TODO: to be fixed properly via #2830, noop for now
};
function isPresent(obj) {
return obj !== undefined && obj !== null;
}
function isBlank(obj) {
return obj === undefined || obj === null;
}
function isString(obj) {
return typeof obj === 'string';
}
function isArray(obj) {
return Array.isArray(obj);
}
var StringWrapper = (function () {
function StringWrapper() {
}
StringWrapper.fromCharCode = function (code) { return String.fromCharCode(code); };
StringWrapper.charCodeAt = function (s, index) { return s.charCodeAt(index); };
StringWrapper.split = function (s, regExp) { return s.split(regExp); };
StringWrapper.equals = function (s, s2) { return s === s2; };
StringWrapper.stripLeft = function (s, charVal) {
if (s && s.length) {
var pos = 0;
for (var i = 0; i < s.length; i++) {
if (s[i] != charVal)
break;
pos++;
}
s = s.substring(pos);
}
return s;
};
StringWrapper.stripRight = function (s, charVal) {
if (s && s.length) {
var pos = s.length;
for (var i = s.length - 1; i >= 0; i--) {
if (s[i] != charVal)
break;
pos--;
}
s = s.substring(0, pos);
}
return s;
};
StringWrapper.replace = function (s, from, replace) {
return s.replace(from, replace);
};
StringWrapper.replaceAll = function (s, from, replace) {
return s.replace(from, replace);
};
StringWrapper.slice = function (s, from, to) {
if (from === void 0) { from = 0; }
if (to === void 0) { to = null; }
return s.slice(from, to === null ? undefined : to);
};
StringWrapper.replaceAllMapped = function (s, from, cb) {
return s.replace(from, function () {
var matches = [];
for (var _i = 0; _i < arguments.length; _i++) {
matches[_i - 0] = arguments[_i];
}
// Remove offset & string from the result array
matches.splice(-2, 2);
// The callback receives match, p1, ..., pn
return cb(matches);
});
};
StringWrapper.contains = function (s, substr) { return s.indexOf(substr) != -1; };
StringWrapper.compare = function (a, b) {
if (a < b) {
return -1;
}
else if (a > b) {
return 1;
}
else {
return 0;
}
};
return StringWrapper;
}());
var NumberWrapper = (function () {
function NumberWrapper() {
}
NumberWrapper.toFixed = function (n, fractionDigits) { return n.toFixed(fractionDigits); };
NumberWrapper.equal = function (a, b) { return a === b; };
NumberWrapper.parseIntAutoRadix = function (text) {
var result = parseInt(text);
if (isNaN(result)) {
throw new Error('Invalid integer literal when parsing ' + text);
}
return result;
};
NumberWrapper.parseInt = function (text, radix) {
if (radix == 10) {
if (/^(\-|\+)?[0-9]+$/.test(text)) {
return parseInt(text, radix);
}
}
else if (radix == 16) {
if (/^(\-|\+)?[0-9ABCDEFabcdef]+$/.test(text)) {
return parseInt(text, radix);
}
}
else {
var result = parseInt(text, radix);
if (!isNaN(result)) {
return result;
}
}
throw new Error('Invalid integer literal when parsing ' + text + ' in base ' + radix);
};
Object.defineProperty(NumberWrapper, "NaN", {
get: function () { return NaN; },
enumerable: true,
configurable: true
});
NumberWrapper.isNumeric = function (value) { return !isNaN(value - parseFloat(value)); };
NumberWrapper.isNaN = function (value) { return isNaN(value); };
NumberWrapper.isInteger = function (value) { return Number.isInteger(value); };
return NumberWrapper;
}());
function isJsObject(o) {
return o !== null && (typeof o === 'function' || typeof o === 'object');
}
// Can't be all uppercase as our transpiler would think it is a special directive...
var Json = (function () {
function Json() {
}
Json.parse = function (s) { return global$1.JSON.parse(s); };
Json.stringify = function (data) {
// Dart doesn't take 3 arguments
return global$1.JSON.stringify(data, null, 2);
};
return Json;
}());
var _symbolIterator = null;
function getSymbolIterator() {
if (isBlank(_symbolIterator)) {
if (isPresent(globalScope.Symbol) && isPresent(Symbol.iterator)) {
_symbolIterator = Symbol.iterator;
}
else {
// es6-shim specific logic
var keys = Object.getOwnPropertyNames(Map.prototype);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (key !== 'entries' && key !== 'size' &&
Map.prototype[key] === Map.prototype['entries']) {
_symbolIterator = key;
}
}
}
}
return _symbolIterator;
}
/**
* @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
*/
/**
* Supported http methods.
* @experimental
*/
exports.RequestMethod;
(function (RequestMethod) {
RequestMethod[RequestMethod["Get"] = 0] = "Get";
RequestMethod[RequestMethod["Post"] = 1] = "Post";
RequestMethod[RequestMethod["Put"] = 2] = "Put";
RequestMethod[RequestMethod["Delete"] = 3] = "Delete";
RequestMethod[RequestMethod["Options"] = 4] = "Options";
RequestMethod[RequestMethod["Head"] = 5] = "Head";
RequestMethod[RequestMethod["Patch"] = 6] = "Patch";
})(exports.RequestMethod || (exports.RequestMethod = {}));
/**
* All possible states in which a connection can be, based on
* [States](http://www.w3.org/TR/XMLHttpRequest/#states) from the `XMLHttpRequest` spec, but with an
* additional "CANCELLED" state.
* @experimental
*/
exports.ReadyState;
(function (ReadyState) {
ReadyState[ReadyState["Unsent"] = 0] = "Unsent";
ReadyState[ReadyState["Open"] = 1] = "Open";
ReadyState[ReadyState["HeadersReceived"] = 2] = "HeadersReceived";
ReadyState[ReadyState["Loading"] = 3] = "Loading";
ReadyState[ReadyState["Done"] = 4] = "Done";
ReadyState[ReadyState["Cancelled"] = 5] = "Cancelled";
})(exports.ReadyState || (exports.ReadyState = {}));
/**
* Acceptable response types to be associated with a {@link Response}, based on
* [ResponseType](https://fetch.spec.whatwg.org/#responsetype) from the Fetch spec.
* @experimental
*/
exports.ResponseType;
(function (ResponseType) {
ResponseType[ResponseType["Basic"] = 0] = "Basic";
ResponseType[ResponseType["Cors"] = 1] = "Cors";
ResponseType[ResponseType["Default"] = 2] = "Default";
ResponseType[ResponseType["Error"] = 3] = "Error";
ResponseType[ResponseType["Opaque"] = 4] = "Opaque";
})(exports.ResponseType || (exports.ResponseType = {}));
/**
* Supported content type to be automatically associated with a {@link Request}.
* @experimental
*/
var ContentType;
(function (ContentType) {
ContentType[ContentType["NONE"] = 0] = "NONE";
ContentType[ContentType["JSON"] = 1] = "JSON";
ContentType[ContentType["FORM"] = 2] = "FORM";
ContentType[ContentType["FORM_DATA"] = 3] = "FORM_DATA";
ContentType[ContentType["TEXT"] = 4] = "TEXT";
ContentType[ContentType["BLOB"] = 5] = "BLOB";
ContentType[ContentType["ARRAY_BUFFER"] = 6] = "ARRAY_BUFFER";
})(ContentType || (ContentType = {}));
/**
* Define which buffer to use to store the response
* @experimental
*/
exports.ResponseContentType;
(function (ResponseContentType) {
ResponseContentType[ResponseContentType["Text"] = 0] = "Text";
ResponseContentType[ResponseContentType["Json"] = 1] = "Json";
ResponseContentType[ResponseContentType["ArrayBuffer"] = 2] = "ArrayBuffer";
ResponseContentType[ResponseContentType["Blob"] = 3] = "Blob";
})(exports.ResponseContentType || (exports.ResponseContentType = {}));
// Safari and Internet Explorer do not support the iterable parameter to the
// Map constructor. We work around that by manually adding the items.
var createMapFromPairs = (function () {
try {
if (new Map([[1, 2]]).size === 1) {
return function createMapFromPairs(pairs) { return new Map(pairs); };
}
}
catch (e) {
}
return function createMapAndPopulateFromPairs(pairs) {
var map = new Map();
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i];
map.set(pair[0], pair[1]);
}
return map;
};
})();
var _clearValues = (function () {
if ((new Map()).keys().next) {
return function _clearValues(m) {
var keyIterator = m.keys();
var k;
while (!((k = keyIterator.next()).done)) {
m.set(k.value, null);
}
};
}
else {
return function _clearValuesWithForeEach(m) {
m.forEach(function (v, k) { m.set(k, null); });
};
}
})();
// Safari doesn't implement MapIterator.next(), which is used is Traceur's polyfill of Array.from
// TODO(mlaval): remove the work around once we have a working polyfill of Array.from
var _arrayFromMap = (function () {
try {
if ((new Map()).values().next) {
return function createArrayFromMap(m, getValues) {
return getValues ? Array.from(m.values()) : Array.from(m.keys());
};
}
}
catch (e) {
}
return function createArrayFromMapWithForeach(m, getValues) {
var res = new Array(m.size), i = 0;
m.forEach(function (v, k) {
res[i] = getValues ? v : k;
i++;
});
return res;
};
})();
var MapWrapper = (function () {
function MapWrapper() {
}
MapWrapper.createFromStringMap = function (stringMap) {
var result = new Map();
for (var prop in stringMap) {
result.set(prop, stringMap[prop]);
}
return result;
};
MapWrapper.toStringMap = function (m) {
var r = {};
m.forEach(function (v, k) { return r[k] = v; });
return r;
};
MapWrapper.createFromPairs = function (pairs) { return createMapFromPairs(pairs); };
MapWrapper.iterable = function (m) { return m; };
MapWrapper.keys = function (m) { return _arrayFromMap(m, false); };
MapWrapper.values = function (m) { return _arrayFromMap(m, true); };
return MapWrapper;
}());
/**
* Wraps Javascript Objects
*/
var StringMapWrapper = (function () {
function StringMapWrapper() {
}
StringMapWrapper.get = function (map, key) {
return map.hasOwnProperty(key) ? map[key] : undefined;
};
StringMapWrapper.set = function (map, key, value) { map[key] = value; };
StringMapWrapper.keys = function (map) { return Object.keys(map); };
StringMapWrapper.values = function (map) {
return Object.keys(map).map(function (k) { return map[k]; });
};
StringMapWrapper.isEmpty = function (map) {
for (var prop in map) {
return false;
}
return true;
};
StringMapWrapper.forEach = function (map, callback) {
for (var _i = 0, _a = Object.keys(map); _i < _a.length; _i++) {
var k = _a[_i];
callback(map[k], k);
}
};
StringMapWrapper.merge = function (m1, m2) {
var m = {};
for (var _i = 0, _a = Object.keys(m1); _i < _a.length; _i++) {
var k = _a[_i];
m[k] = m1[k];
}
for (var _b = 0, _c = Object.keys(m2); _b < _c.length; _b++) {
var k = _c[_b];
m[k] = m2[k];
}
return m;
};
StringMapWrapper.equals = function (m1, m2) {
var k1 = Object.keys(m1);
var k2 = Object.keys(m2);
if (k1.length != k2.length) {
return false;
}
for (var i = 0; i < k1.length; i++) {
var key = k1[i];
if (m1[key] !== m2[key]) {
return false;
}
}
return true;
};
return StringMapWrapper;
}());
var ListWrapper = (function () {
function ListWrapper() {
}
// JS has no way to express a statically fixed size list, but dart does so we
// keep both methods.
ListWrapper.createFixedSize = function (size) { return new Array(size); };
ListWrapper.createGrowableSize = function (size) { return new Array(size); };
ListWrapper.clone = function (array) { return array.slice(0); };
ListWrapper.forEachWithIndex = function (array, fn) {
for (var i = 0; i < array.length; i++) {
fn(array[i], i);
}
};
ListWrapper.first = function (array) {
if (!array)
return null;
return array[0];
};
ListWrapper.last = function (array) {
if (!array || array.length == 0)
return null;
return array[array.length - 1];
};
ListWrapper.indexOf = function (array, value, startIndex) {
if (startIndex === void 0) { startIndex = 0; }
return array.indexOf(value, startIndex);
};
ListWrapper.contains = function (list, el) { return list.indexOf(el) !== -1; };
ListWrapper.reversed = function (array) {
var a = ListWrapper.clone(array);
return a.reverse();
};
ListWrapper.concat = function (a, b) { return a.concat(b); };
ListWrapper.insert = function (list, index, value) { list.splice(index, 0, value); };
ListWrapper.removeAt = function (list, index) {
var res = list[index];
list.splice(index, 1);
return res;
};
ListWrapper.removeAll = function (list, items) {
for (var i = 0; i < items.length; ++i) {
var index = list.indexOf(items[i]);
list.splice(index, 1);
}
};
ListWrapper.remove = function (list, el) {
var index = list.indexOf(el);
if (index > -1) {
list.splice(index, 1);
return true;
}
return false;
};
ListWrapper.clear = function (list) { list.length = 0; };
ListWrapper.isEmpty = function (list) { return list.length == 0; };
ListWrapper.fill = function (list, value, start, end) {
if (start === void 0) { start = 0; }
if (end === void 0) { end = null; }
list.fill(value, start, end === null ? list.length : end);
};
ListWrapper.equals = function (a, b) {
if (a.length != b.length)
return false;
for (var i = 0; i < a.length; ++i) {
if (a[i] !== b[i])
return false;
}
return true;
};
ListWrapper.slice = function (l, from, to) {
if (from === void 0) { from = 0; }
if (to === void 0) { to = null; }
return l.slice(from, to === null ? undefined : to);
};
ListWrapper.splice = function (l, from, length) { return l.splice(from, length); };
ListWrapper.sort = function (l, compareFn) {
if (isPresent(compareFn)) {
l.sort(compareFn);
}
else {
l.sort();
}
};
ListWrapper.toString = function (l) { return l.toString(); };
ListWrapper.toJSON = function (l) { return JSON.stringify(l); };
ListWrapper.maximum = function (list, predicate) {
if (list.length == 0) {
return null;
}
var solution = null;
var maxValue = -Infinity;
for (var index = 0; index < list.length; index++) {
var candidate = list[index];
if (isBlank(candidate)) {
continue;
}
var candidateValue = predicate(candidate);
if (candidateValue > maxValue) {
solution = candidate;
maxValue = candidateValue;
}
}
return solution;
};
ListWrapper.flatten = function (list) {
var target = [];
_flattenArray(list, target);
return target;
};
ListWrapper.addAll = function (list, source) {
for (var i = 0; i < source.length; i++) {
list.push(source[i]);
}
};
return ListWrapper;
}());
function _flattenArray(source, target) {
if (isPresent(source)) {
for (var i = 0; i < source.length; i++) {
var item = source[i];
if (isArray(item)) {
_flattenArray(item, target);
}
else {
target.push(item);
}
}
}
return target;
}
function isListLikeIterable(obj) {
if (!isJsObject(obj))
return false;
return isArray(obj) ||
(!(obj instanceof Map) &&
getSymbolIterator() in obj); // JS Iterable have a Symbol.iterator prop
}
function iterateListLike(obj, fn) {
if (isArray(obj)) {
for (var i = 0; i < obj.length; i++) {
fn(obj[i]);
}
}
else {
var iterator = obj[getSymbolIterator()]();
var item;
while (!((item = iterator.next()).done)) {
fn(item.value);
}
}
}
/**
* Polyfill for [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers/Headers), as
* specified in the [Fetch Spec](https://fetch.spec.whatwg.org/#headers-class).
*
* The only known difference between this `Headers` implementation and the spec is the
* lack of an `entries` method.
*
* ### Example ([live demo](http://plnkr.co/edit/MTdwT6?p=preview))
*
* ```
* import {Headers} from '@angular/http';
*
* var firstHeaders = new Headers();
* firstHeaders.append('Content-Type', 'image/jpeg');
* console.log(firstHeaders.get('Content-Type')) //'image/jpeg'
*
* // Create headers from Plain Old JavaScript Object
* var secondHeaders = new Headers({
* 'X-My-Custom-Header': 'Angular'
* });
* console.log(secondHeaders.get('X-My-Custom-Header')); //'Angular'
*
* var thirdHeaders = new Headers(secondHeaders);
* console.log(thirdHeaders.get('X-My-Custom-Header')); //'Angular'
* ```
*
* @experimental
*/
var Headers = (function () {
function Headers(headers) {
var _this = this;
if (headers instanceof Headers) {
this._headersMap = new Map(headers._headersMap);
return;
}
this._headersMap = new Map();
if (isBlank(headers)) {
return;
}
// headers instanceof StringMap
StringMapWrapper.forEach(headers, function (v, k) {
_this._headersMap.set(normalize(k), isListLikeIterable(v) ? v : [v]);
});
}
/**
* Returns a new Headers instance from the given DOMString of Response Headers
*/
Headers.fromResponseHeaderString = function (headersString) {
var headers = new Headers();
headersString.split('\n').forEach(function (line) {
var index = line.indexOf(':');
if (index > 0) {
var key = line.substring(0, index);
var value = line.substring(index + 1).trim();
headers.set(key, value);
}
});
return headers;
};
/**
* Appends a header to existing list of header values for a given header name.
*/
Headers.prototype.append = function (name, value) {
name = normalize(name);
var mapName = this._headersMap.get(name);
var list = isListLikeIterable(mapName) ? mapName : [];
list.push(value);
this._headersMap.set(name, list);
};
/**
* Deletes all header values for the given name.
*/
Headers.prototype.delete = function (name) { this._headersMap.delete(normalize(name)); };
Headers.prototype.forEach = function (fn) {
this._headersMap.forEach(fn);
};
/**
* Returns first header that matches given name.
*/
Headers.prototype.get = function (header) { return ListWrapper.first(this._headersMap.get(normalize(header))); };
/**
* Check for existence of header by given name.
*/
Headers.prototype.has = function (header) { return this._headersMap.has(normalize(header)); };
/**
* Provides names of set headers
*/
Headers.prototype.keys = function () { return MapWrapper.keys(this._headersMap); };
/**
* Sets or overrides header value for given name.
*/
Headers.prototype.set = function (header, value) {
var list = [];
if (isListLikeIterable(value)) {
var pushValue = value.join(',');
list.push(pushValue);
}
else {
list.push(value);
}
this._headersMap.set(normalize(header), list);
};
/**
* Returns values of all headers.
*/
Headers.prototype.values = function () { return MapWrapper.values(this._headersMap); };
/**
* Returns string of all headers.
*/
Headers.prototype.toJSON = function () {
var serializableHeaders = {};
this._headersMap.forEach(function (values, name) {
var list = [];
iterateListLike(values, function (val /** TODO #9100 */) { return list = ListWrapper.concat(list, val.split(',')); });
serializableHeaders[normalize(name)] = list;
});
return serializableHeaders;
};
/**
* Returns list of header values for a given name.
*/
Headers.prototype.getAll = function (header) {
var headers = this._headersMap.get(normalize(header));
return isListLikeIterable(headers) ? headers : [];
};
/**
* This method is not implemented.
*/
Headers.prototype.entries = function () { throw new Error('"entries" method is not implemented on Headers class'); };
return Headers;
}());
// "HTTP character sets are identified by case-insensitive tokens"
// Spec at https://tools.ietf.org/html/rfc2616
// This implementation is same as NodeJS.
// see https://nodejs.org/dist/latest-v6.x/docs/api/http.html#http_message_headers
function normalize(name) {
return name.toLowerCase();
}
/**
* @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
*/
var __extends$1 = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/**
* Creates a response options object to be optionally provided when instantiating a
* {@link Response}.
*
* This class is based on the `ResponseInit` description in the [Fetch
* Spec](https://fetch.spec.whatwg.org/#responseinit).
*
* All values are null by default. Typical defaults can be found in the
* {@link BaseResponseOptions} class, which sub-classes `ResponseOptions`.
*
* This class may be used in tests to build {@link Response Responses} for
* mock responses (see {@link MockBackend}).
*
* ### Example ([live demo](http://plnkr.co/edit/P9Jkk8e8cz6NVzbcxEsD?p=preview))
*
* ```typescript
* import {ResponseOptions, Response} from '@angular/http';
*
* var options = new ResponseOptions({
* body: '{"name":"Jeff"}'
* });
* var res = new Response(options);
*
* console.log('res.json():', res.json()); // Object {name: "Jeff"}
* ```
*
* @experimental
*/
var ResponseOptions = (function () {
function ResponseOptions(_a) {
var _b = _a === void 0 ? {} : _a, body = _b.body, status = _b.status, headers = _b.headers, statusText = _b.statusText, type = _b.type, url = _b.url;
this.body = isPresent(body) ? body : null;
this.status = isPresent(status) ? status : null;
this.headers = isPresent(headers) ? headers : null;
this.statusText = isPresent(statusText) ? statusText : null;
this.type = isPresent(type) ? type : null;
this.url = isPresent(url) ? url : null;
}
/**
* Creates a copy of the `ResponseOptions` instance, using the optional input as values to
* override
* existing values. This method will not change the values of the instance on which it is being
* called.
*
* This may be useful when sharing a base `ResponseOptions` object inside tests,
* where certain properties may change from test to test.
*
* ### Example ([live demo](http://plnkr.co/edit/1lXquqFfgduTFBWjNoRE?p=preview))
*
* ```typescript
* import {ResponseOptions, Response} from '@angular/http';
*
* var options = new ResponseOptions({
* body: {name: 'Jeff'}
* });
* var res = new Response(options.merge({
* url: 'https://google.com'
* }));
* console.log('options.url:', options.url); // null
* console.log('res.json():', res.json()); // Object {name: "Jeff"}
* console.log('res.url:', res.url); // https://google.com
* ```
*/
ResponseOptions.prototype.merge = function (options) {
return new ResponseOptions({
body: isPresent(options) && isPresent(options.body) ? options.body : this.body,
status: isPresent(options) && isPresent(options.status) ? options.status : this.status,
headers: isPresent(options) && isPresent(options.headers) ? options.headers : this.headers,
statusText: isPresent(options) && isPresent(options.statusText) ? options.statusText :
this.statusText,
type: isPresent(options) && isPresent(options.type) ? options.type : this.type,
url: isPresent(options) && isPresent(options.url) ? options.url : this.url,
});
};
return ResponseOptions;
}());
/**
* Subclass of {@link ResponseOptions}, with default values.
*
* Default values:
* * status: 200
* * headers: empty {@link Headers} object
*
* This class could be extended and bound to the {@link ResponseOptions} class
* when configuring an {@link Injector}, in order to override the default options
* used by {@link Http} to create {@link Response Responses}.
*
* ### Example ([live demo](http://plnkr.co/edit/qv8DLT?p=preview))
*
* ```typescript
* import {provide} from '@angular/core';
* import {bootstrap} from '@angular/platform-browser/browser';
* import {HTTP_PROVIDERS, Headers, Http, BaseResponseOptions, ResponseOptions} from
* '@angular/http';
* import {App} from './myapp';
*
* class MyOptions extends BaseResponseOptions {
* headers:Headers = new Headers({network: 'github'});
* }
*
* bootstrap(App, [HTTP_PROVIDERS, {provide: ResponseOptions, useClass: MyOptions}]);
* ```
*
* The options could also be extended when manually creating a {@link Response}
* object.
*
* ### Example ([live demo](http://plnkr.co/edit/VngosOWiaExEtbstDoix?p=preview))
*
* ```
* import {BaseResponseOptions, Response} from '@angular/http';
*
* var options = new BaseResponseOptions();
* var res = new Response(options.merge({
* body: 'Angular',
* headers: new Headers({framework: 'angular'})
* }));
* console.log('res.headers.get("framework"):', res.headers.get('framework')); // angular
* console.log('res.text():', res.text()); // Angular;
* ```
*
* @experimental
*/
var BaseResponseOptions = (function (_super) {
__extends$1(BaseResponseOptions, _super);
function BaseResponseOptions() {
_super.call(this, { status: 200, statusText: 'Ok', type: exports.ResponseType.Default, headers: new Headers() });
}
BaseResponseOptions.decorators = [
{ type: _angular_core.Injectable },
];
/** @nocollapse */
BaseResponseOptions.ctorParameters = [];
return BaseResponseOptions;
}(ResponseOptions));
/**
* @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
*/
/**
* Abstract class from which real backends are derived.
*
* The primary purpose of a `ConnectionBackend` is to create new connections to fulfill a given
* {@link Request}.
*
* @experimental
*/
var ConnectionBackend = (function () {
function ConnectionBackend() {
}
return ConnectionBackend;
}());
/**
* Abstract class from which real connections are derived.
*
* @experimental
*/
var Connection = (function () {
function Connection() {
}
return Connection;
}());
/**
* An XSRFStrategy configures XSRF protection (e.g. via headers) on an HTTP request.
*
* @experimental
*/
var XSRFStrategy = (function () {
function XSRFStrategy() {
}
return XSRFStrategy;
}());
function normalizeMethodName(method) {
if (isString(method)) {
var originalMethod = method;
method = method
.replace(/(\w)(\w*)/g, function (g0, g1, g2) { return g1.toUpperCase() + g2.toLowerCase(); });
method = exports.RequestMethod[method];
if (typeof method !== 'number')
throw new Error("Invalid request method. The method \"" + originalMethod + "\" is not supported.");
}
return method;
}
var isSuccess = function (status) { return (status >= 200 && status < 300); };
function getResponseURL(xhr) {
if ('responseURL' in xhr) {
return xhr.responseURL;
}
if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
return xhr.getResponseHeader('X-Request-URL');
}
return;
}
function stringToArrayBuffer(input) {
var view = new Uint16Array(input.length);
for (var i = 0, strLen = input.length; i < strLen; i++) {
view[i] = input.charCodeAt(i);
}
return view.buffer;
}
/**
* @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
*/
function paramParser(rawParams) {
if (rawParams === void 0) { rawParams = ''; }
var map = new Map();
if (rawParams.length > 0) {
var params = rawParams.split('&');
params.forEach(function (param) {
var eqIdx = param.indexOf('=');
var _a = eqIdx == -1 ? [param, ''] : [param.slice(0, eqIdx), param.slice(eqIdx + 1)], key = _a[0], val = _a[1];
var list = map.get(key) || [];
list.push(val);
map.set(key, list);
});
}
return map;
}
/**
* @experimental
**/
var QueryEncoder = (function () {
function QueryEncoder() {
}
QueryEncoder.prototype.encodeKey = function (k) { return standardEncoding(k); };
QueryEncoder.prototype.encodeValue = function (v) { return standardEncoding(v); };
return QueryEncoder;
}());
function standardEncoding(v) {
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, '/');
}
/**
* Map-like representation of url search parameters, based on
* [URLSearchParams](https://url.spec.whatwg.org/#urlsearchparams) in the url living standard,
* with several extensions for merging URLSearchParams objects:
* - setAll()
* - appendAll()
* - replaceAll()
*
* This class accepts an optional second parameter of ${@link QueryEncoder},
* which is used to serialize parameters before making a request. By default,
* `QueryEncoder` encodes keys and values of parameters using `encodeURIComponent`,
* and then un-encodes certain characters that are allowed to be part of the query
* according to IETF RFC 3986: https://tools.ietf.org/html/rfc3986.
*
* These are the characters that are not encoded: `! $ \' ( ) * + , ; A 9 - . _ ~ ? /`
*
* If the set of allowed query characters is not acceptable for a particular backend,
* `QueryEncoder` can be subclassed and provided as the 2nd argument to URLSearchParams.
*
* ```
* import {URLSearchParams, QueryEncoder} from '@angular/http';
* class MyQueryEncoder extends QueryEncoder {
* encodeKey(k: string): string {
* return myEncodingFunction(k);
* }
*
* encodeValue(v: string): string {
* return myEncodingFunction(v);
* }
* }
*
* let params = new URLSearchParams('', new MyQueryEncoder());
* ```
* @experimental
*/
var URLSearchParams = (function () {
function URLSearchParams(rawParams, queryEncoder) {
if (rawParams === void 0) { rawParams = ''; }
if (queryEncoder === void 0) { queryEncoder = new QueryEncoder(); }
this.rawParams = rawParams;
this.queryEncoder = queryEncoder;
this.paramsMap = paramParser(rawParams);
}
URLSearchParams.prototype.clone = function () {
var clone = new URLSearchParams('', this.queryEncoder);
clone.appendAll(this);
return clone;
};
URLSearchParams.prototype.has = function (param) { return this.paramsMap.has(param); };
URLSearchParams.prototype.get = function (param) {
var storedParam = this.paramsMap.get(param);
return Array.isArray(storedParam) ? storedParam[0] : null;
};
URLSearchParams.prototype.getAll = function (param) { return this.paramsMap.get(param) || []; };
URLSearchParams.prototype.set = function (param, val) {
var list = this.paramsMap.get(param) || [];
list.length = 0;
list.push(val);
this.paramsMap.set(param, list);
};
// A merge operation
// For each name-values pair in `searchParams`, perform `set(name, values[0])`
//
// E.g: "a=[1,2,3], c=[8]" + "a=[4,5,6], b=[7]" = "a=[4], c=[8], b=[7]"
//
// TODO(@caitp): document this better
URLSearchParams.prototype.setAll = function (searchParams) {
var _this = this;
searchParams.paramsMap.forEach(function (value, param) {
var list = _this.paramsMap.get(param) || [];
list.length = 0;
list.push(value[0]);
_this.paramsMap.set(param, list);
});
};
URLSearchParams.prototype.append = function (param, val) {
var list = this.paramsMap.get(param) || [];
list.push(val);
this.paramsMap.set(param, list);
};
// A merge operation
// For each name-values pair in `searchParams`, perform `append(name, value)`
// for each value in `values`.
//
// E.g: "a=[1,2], c=[8]" + "a=[3,4], b=[7]" = "a=[1,2,3,4], c=[8], b=[7]"
//
// TODO(@caitp): document this better
URLSearchParams.prototype.appendAll = function (searchParams) {
var _this = this;
searchParams.paramsMap.forEach(function (value, param) {
var list = _this.paramsMap.get(param) || [];
for (var i = 0; i < value.length; ++i) {
list.push(value[i]);
}
_this.paramsMap.set(param, list);
});
};
// A merge operation
// For each name-values pair in `searchParams`, perform `delete(name)`,
// followed by `set(name, values)`
//
// E.g: "a=[1,2,3], c=[8]" + "a=[4,5,6], b=[7]" = "a=[4,5,6], c=[8], b=[7]"
//
// TODO(@caitp): document this better
URLSearchParams.prototype.replaceAll = function (searchParams) {
var _this = this;
searchParams.paramsMap.forEach(function (value, param) {
var list = _this.paramsMap.get(param) || [];
list.length = 0;
for (var i = 0; i < value.length; ++i) {
list.push(value[i]);
}
_this.paramsMap.set(param, list);
});
};
URLSearchParams.prototype.toString = function () {
var _this = this;
var paramsList = [];
this.paramsMap.forEach(function (values, k) {
values.forEach(function (v) { return paramsList.push(_this.queryEncoder.encodeKey(k) + '=' + _this.queryEncoder.encodeValue(v)); });
});
return paramsList.join('&');
};
URLSearchParams.prototype.delete = function (param) { this.paramsMap.delete(param); };
return URLSearchParams;
}());
/**
* HTTP request body used by both {@link Request} and {@link Response}
* https://fetch.spec.whatwg.org/#body
*/
var Body = (function () {
function Body() {
}
/**
* Attempts to return body as parsed `JSON` object, or raises an exception.
*/
Body.prototype.json = function () {
if (isString(this._body)) {
return Json.parse(this._body);
}
if (this._body instanceof ArrayBuffer) {
return Json.parse(this.text());
}
return this._body;
};
/**
* Returns the body as a string, presuming `toString()` can be called on the response body.
*/
Body.prototype.text = function () {
if (this._body instanceof URLSearchParams) {
return this._body.toString();
}
if (this._body instanceof ArrayBuffer) {
return String.fromCharCode.apply(null, new Uint16Array(this._body));
}
if (this._body === null) {
return '';
}
if (isJsObject(this._body)) {
return Json.stringify(this._body);
}
return this._body.toString();
};
/**
* Return the body as an ArrayBuffer
*/
Body.prototype.arrayBuffer = function () {
if (this._body instanceof ArrayBuffer) {
return this._body;
}
return stringToArrayBuffer(this.text());
};
/**
* Returns the request's body as a Blob, assuming that body exists.
*/
Body.prototype.blob = function () {
if (this._body instanceof Blob) {
return this._body;
}
if (this._body instanceof ArrayBuffer) {
return new Blob([this._body]);
}
throw new Error('The request body isn\'t either a blob or an array buffer');
};
return Body;
}());
/**
* @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
*/
var __extends$2 = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/**
* Creates `Response` instances from provided values.
*
* Though this object isn't
* usually instantiated by end-users, it is the primary object interacted with when it comes time to
* add data to a view.
*
* ### Example
*
* ```
* http.request('my-friends.txt').subscribe(response => this.friends = response.text());
* ```
*
* The Response's interface is inspired by the Response constructor defined in the [Fetch
* Spec](https://fetch.spec.whatwg.org/#response-class), but is considered a static value whose body
* can be accessed many times. There are other differences in the implementation, but this is the
* most significant.
*
* @experimental
*/
var Response = (function (_super) {
__extends$2(Response, _super);
function Response(responseOptions) {
_super.call(this);
this._body = responseOptions.body;
this.status = responseOptions.status;
this.ok = (this.status >= 200 && this.status <= 299);
this.statusText = responseOptions.statusText;
this.headers = responseOptions.headers;
this.type = responseOptions.type;
this.url = responseOptions.url;
}
Response.prototype.toString = function () {
return "Response with status: " + this.status + " " + this.statusText + " for URL: " + this.url;
};
return Response;
}(Body));
var _nextRequestId = 0;
var JSONP_HOME = '__ng_jsonp__';
var _jsonpConnections = null;
function _getJsonpConnections() {
if (_jsonpConnections === null) {
_jsonpConnections = global$1[JSONP_HOME] = {};
}
return _jsonpConnections;
}
// Make sure not to evaluate this in a non-browser environment!
var BrowserJsonp = (function () {
function BrowserJsonp() {
}
// Construct a <script> element with the specified URL
BrowserJsonp.prototype.build = function (url) {
var node = document.createElement('script');
node.src = url;
return node;
};
BrowserJsonp.prototype.nextRequestID = function () { return "__req" + _nextRequestId++; };
BrowserJsonp.prototype.requestCallback = function (id) { return JSONP_HOME + "." + id + ".finished"; };
BrowserJsonp.prototype.exposeConnection = function (id, connection) {
var connections = _getJsonpConnections();
connections[id] = connection;
};
BrowserJsonp.prototype.removeConnection = function (id) {
var connections = _getJsonpConnections();
connections[id] = null;
};
// Attach the <script> element to the DOM
BrowserJsonp.prototype.send = function (node) { document.body.appendChild((node)); };
// Remove <script> element from the DOM
BrowserJsonp.prototype.cleanup = function (node) {
if (node.parentNode) {
node.parentNode.removeChild((node));
}
};
BrowserJsonp.decorators = [
{ type: _angular_core.Injectable },
];
/** @nocollapse */
BrowserJsonp.ctorParameters = [];
return BrowserJsonp;
}());
/**
* @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
*/
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var JSONP_ERR_NO_CALLBACK = 'JSONP injected script did not invoke callback.';
var JSONP_ERR_WRONG_METHOD = 'JSONP requests must use GET request method.';
/**
* Abstract base class for an in-flight JSONP request.
*
* @experimental
*/
var JSONPConnection = (function () {
function JSONPConnection() {
}
return JSONPConnection;
}());
var JSONPConnection_ = (function (_super) {
__extends(JSONPConnection_, _super);
function JSONPConnection_(req, _dom, baseResponseOptions) {
var _this = this;
_super.call(this);
this._dom = _dom;
this.baseResponseOptions = baseResponseOptions;
this._finished = false;
if (req.method !== exports.RequestMethod.Get) {
throw new TypeError(JSONP_ERR_WRONG_METHOD);
}
this.request = r