2016-02-08 13:24:09 -08:00
|
|
|
import {PromiseWrapper, PromiseCompleter} from 'angular2/src/facade/promise';
|
2015-11-06 17:34:07 -08:00
|
|
|
import {isPresent} from 'angular2/src/facade/lang';
|
2015-11-13 11:21:16 -08:00
|
|
|
import {XHR} from 'angular2/src/compiler/xhr';
|
2015-01-30 09:43:21 +01:00
|
|
|
|
|
|
|
export class XHRImpl extends XHR {
|
|
|
|
get(url: string): Promise<string> {
|
2015-07-24 17:24:28 -07:00
|
|
|
var completer: PromiseCompleter < string >= PromiseWrapper.completer();
|
2015-01-30 09:43:21 +01:00
|
|
|
var xhr = new XMLHttpRequest();
|
|
|
|
xhr.open('GET', url, true);
|
|
|
|
xhr.responseType = 'text';
|
|
|
|
|
|
|
|
xhr.onload = function() {
|
2015-06-16 23:15:26 -07:00
|
|
|
// responseText is the old-school way of retrieving response (supported by IE8 & 9)
|
|
|
|
// response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
|
2015-07-27 17:01:05 -07:00
|
|
|
var response = isPresent(xhr.response) ? xhr.response : xhr.responseText;
|
2015-06-16 23:15:26 -07:00
|
|
|
|
|
|
|
// normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
|
|
|
|
var status = xhr.status === 1223 ? 204 : xhr.status;
|
|
|
|
|
|
|
|
// fix status code when it is 0 (0 status is undocumented).
|
|
|
|
// Occurs when accessing file resources or on Android 4.1 stock browser
|
|
|
|
// while retrieving files from application cache.
|
|
|
|
if (status === 0) {
|
|
|
|
status = response ? 200 : 0;
|
|
|
|
}
|
|
|
|
|
2015-01-30 09:43:21 +01:00
|
|
|
if (200 <= status && status <= 300) {
|
2015-06-16 23:15:26 -07:00
|
|
|
completer.resolve(response);
|
2015-01-30 09:43:21 +01:00
|
|
|
} else {
|
2015-05-19 19:27:03 +02:00
|
|
|
completer.reject(`Failed to load ${url}`, null);
|
2015-01-30 09:43:21 +01:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2015-05-19 19:27:03 +02:00
|
|
|
xhr.onerror = function() { completer.reject(`Failed to load ${url}`, null); };
|
2015-01-30 09:43:21 +01:00
|
|
|
|
|
|
|
xhr.send();
|
|
|
|
return completer.promise;
|
|
|
|
}
|
|
|
|
}
|