2015-05-18 11:57:20 -07:00
|
|
|
import {Injectable} from 'angular2/di';
|
2015-03-23 14:10:55 -07:00
|
|
|
import {isBlank, isPresent, BaseException, stringify} from 'angular2/src/facade/lang';
|
|
|
|
import {Map, MapWrapper, StringMapWrapper, StringMap} from 'angular2/src/facade/collection';
|
|
|
|
import {PromiseWrapper, Promise} from 'angular2/src/facade/async';
|
|
|
|
import {DOM} from 'angular2/src/dom/dom_adapter';
|
|
|
|
|
|
|
|
import {XHR} from 'angular2/src/services/xhr';
|
|
|
|
|
2015-04-09 21:20:11 +02:00
|
|
|
import {ViewDefinition} from '../../api';
|
2015-03-23 14:10:55 -07:00
|
|
|
import {UrlResolver} from 'angular2/src/services/url_resolver';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Strategy to load component templates.
|
2015-04-13 21:00:52 -07:00
|
|
|
* TODO: Make public API once we are more confident in this approach.
|
2015-03-23 14:10:55 -07:00
|
|
|
*/
|
2015-04-02 14:40:49 -07:00
|
|
|
@Injectable()
|
2015-03-23 14:10:55 -07:00
|
|
|
export class TemplateLoader {
|
|
|
|
_xhr: XHR;
|
2015-05-18 11:57:20 -07:00
|
|
|
_htmlCache: StringMap<string, /*element*/ any>;
|
2015-03-23 14:10:55 -07:00
|
|
|
|
|
|
|
constructor(xhr: XHR, urlResolver: UrlResolver) {
|
|
|
|
this._xhr = xhr;
|
|
|
|
this._htmlCache = StringMapWrapper.create();
|
|
|
|
}
|
|
|
|
|
2015-05-18 11:57:20 -07:00
|
|
|
load(template: ViewDefinition): Promise</*element*/ any> {
|
2015-04-09 21:20:11 +02:00
|
|
|
if (isPresent(template.template)) {
|
|
|
|
return PromiseWrapper.resolve(DOM.createTemplate(template.template));
|
2015-03-23 14:10:55 -07:00
|
|
|
}
|
|
|
|
var url = template.absUrl;
|
|
|
|
if (isPresent(url)) {
|
|
|
|
var promise = StringMapWrapper.get(this._htmlCache, url);
|
|
|
|
|
|
|
|
if (isBlank(promise)) {
|
2015-06-01 11:07:14 +02:00
|
|
|
// TODO(vicb): change error when TS gets fixed
|
|
|
|
// https://github.com/angular/angular/issues/2280
|
|
|
|
// throw new BaseException(`Failed to fetch url "${url}"`);
|
|
|
|
promise = PromiseWrapper.then(this._xhr.get(url), html => {
|
2015-03-23 14:10:55 -07:00
|
|
|
var template = DOM.createTemplate(html);
|
|
|
|
return template;
|
2015-06-01 11:07:14 +02:00
|
|
|
}, _ => PromiseWrapper.reject(new BaseException(`Failed to fetch url "${url}"`), null));
|
|
|
|
|
2015-03-23 14:10:55 -07:00
|
|
|
StringMapWrapper.set(this._htmlCache, url, promise);
|
|
|
|
}
|
|
|
|
|
2015-04-30 15:27:28 -07:00
|
|
|
// We need to clone the result as others might change it
|
|
|
|
// (e.g. the compiler).
|
2015-05-18 11:57:20 -07:00
|
|
|
return promise.then((tplElement) => DOM.clone(tplElement));
|
2015-03-23 14:10:55 -07:00
|
|
|
}
|
|
|
|
|
2015-04-09 21:20:11 +02:00
|
|
|
throw new BaseException('View should have either the url or template property set');
|
2015-03-23 14:10:55 -07:00
|
|
|
}
|
|
|
|
}
|