我在Angular2中开发一个模块,以显示与其资源(图像和样式表)放在同一文件夹中的静态html。 html中的路径是相对的,这意味着当html加载到我的Angular组件中时,链接会中断。
如果我使用Angular 1x,我可能会使用ng-include将html注入容器中,如果我错了,请纠正我。我已经开始创建一个管道来查找html中的所有图像实例并更改其路径:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'resourcePath' })
export class ResourcePathPipe implements PipeTransform {
transform(html: string, folder: string): any {
if (!html) return html;
let search = 'src="',
filtered = html.substr(0, html.indexOf(search)),
replacement = 'src="http://' + window.location.host + '/files/uploads/parentFolder/' + folder + '/';
for (let index = html.indexOf(search); index >= 0; index = html.indexOf(search, index + 1)) {
let chunk = html.substr(index, html.indexOf(search, index + 1));
if (chunk.length > 0) {
filtered += replacement + chunk.substr(5);
} else {
let end = html.substr(html.lastIndexOf(search) + replacement.length, html.length);
filtered += end;
console.log("Completed!");
}
}
return filtered;
}
}
我得到了非常不一致的结果,有时完全缺少src
属性。如果有人知道更好的方法来实现这一目标,我将非常感谢这一见解。
更新
这是我通过管道测试的HTML片段:
<div id="pf1" class="pf w0 h0" data-page-no="1"><div class="pc pc1 w0 h0"><img class="bi x0 y0 w1 h1" alt="" src="bg1.png"/></div><div class="pi" data-data='{"ctm":[1.000000,0.000000,0.000000,1.000000,0.000000,0.000000]}'></div></div>