当我的静态文件位于具有不同 URL 的 CDN 上时,如何使用 AngularDart? [英] How do I use AngularDart when my static files are on a CDN with a varying URL?
问题描述
我将 AngularDart 用于我的一个新应用程序.我有一个像这样设置的组件:
I'm using AngularDart for a new application of mine. I have a component set up like so:
@NgComponent(
selector: 'game-timeline',
templateUrl: '/static/dart/game/web/views/timelineview.html',
cssUrl: '/static/dart/game/web/views/timelineview.css',
publishAs: 'ctrl'
)
但我的问题是,在构建时不一定知道模板和 css 位置.它们将位于带有唯一部署标识符的 CDN 上.像……
But my problem is, the template and css locations aren't necessarily known at build-time. They'll be on a CDN with a unique deploy-identifier on them. Something like...
http://cdn.domain.com/static/30294832098/dart/game/web/views/timelineview.html
而且这个数字因每次部署而异.
And that number varies every deploy.
该路径似乎与其托管的 html 页面相关,但不在 CDN 上,因此我不能只使用相对路径 (../blah/blah)
The path seems to be relative to the html page it's hosted on, which is not on the CDN, so I can't just use a relative path (../blah/blah)
我可以在页面中注入一个 JS 变量,告诉我它的静态根在哪里,如果有帮助的话.
I can inject a JS variable into the page telling me where the static root it, if that helps.
主要的 .dart/.js 文件是从 CDN 加载的,但我似乎无法让它与它相关.
The main .dart/.js file is loaded from the CDN, but I can't seem to make it be relative to that.
有什么想法吗?
更新,这是我的完整解决方案,改编自 pavelgj 的精彩答案,该答案读取页面上名为 STATIC_URL 的 js 变量.
Update, here's my full solution adapted from pavelgj's great answer that reads in a js variable called STATIC_URL on the page.
import 'package:angular/angular.dart';
import 'package:js/js.dart' as js;
class CDNRewriter implements UrlRewriter {
String staticUrl;
CDNRewriter() {
var context = js.context;
staticUrl = js.context.STATIC_URL;
}
String call(String url) {
if (url.startsWith('/static/')) {
return _rewriteCdnUrl(url);
}
return url;
}
String _rewriteCdnUrl(String url) {
return url.replaceFirst(new RegExp(r'/static/'), staticUrl);
}
}
推荐答案
您可以实现自定义 UrlRewriter
.UrlRewriter
为通过 angular Http
服务,包括模板和 css.
You can implement a custom UrlRewriter
. UrlRewriter
is called for all resources fetched via angular Http
service, including templates and css.
class MyUrlRewriter implements UrlRewriter {
String call(String url) {
if (url.startsWith('/static/')) {
return _rewriteCdnUrl(url);
}
return url;
}
}
myModule.type(UrlRewriter, implementedBy: MyUrlRewriter);
这篇关于当我的静态文件位于具有不同 URL 的 CDN 上时,如何使用 AngularDart?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!