Angular2 - Class - UrlResolver

UrlResolver 具有非常实际的用途,特别在部署上

Used by the Compiler when resolving HTML and CSS template URLs.

This class can be overridden by the application developer to create custom behavior.

注意: 针对的是HTML 和css 路径。

不代表其他import的路径


Solution1:

通过修改PACKAGE_ROOT_URL来变动baseUrl

import {provide,PACKAGE_ROOT_URL} from 'angular2/core';

bootstrap(AppComponent,[provide(PACKAGE_ROOT_URL,{useValue: '/components'})]);

使用的时候需要package:前缀

templateUrl: 'package:x.html',

会去寻找的目录就是/components/x.html


Solution2:

import {UrlResolver} from 'angular2/compiler';

class MyUrlResolver extends UrlResolver {
resolve(baseUrl: string, url: string): string {
// Serve CSS files from a special CDN.
if (url.substr(-4) === '.css') {
return super.resolve('http://cdn.myapp.com/css/', url);
}
return super.resolve(baseUrl, url);
}
}

bootstrap(AppComponent,[provide(UrlResolver, {useClass: MyUrlResolver})]);

通过override UrlResolver 实现cdn取资源
使用时无需package:

templateUrl: 'x.html',

Solution3:

import {UrlResolver} from 'angular2/compiler';

class MyUrlResolver extends UrlResolver {
resolve(baseUrl: string, url: string): string {

return super.resolve('/compo/', url);
}
}

bootstrap(AppComponent,[provide(UrlResolver, {useClass: MyUrlResolver})]);

使用时不用package:

templateUrl: 'x.html',