Angular使用innerHTML加载HTML文件仅显示链接怎么解决
解决方案
1. 修正ContentService实现(核心问题)
你未贴出ContentService的代码,绝大多数该类问题都是服务实现不符合要求导致的。需要在服务中完成「请求静态HTML文件」+「安全内容过滤」两个操作,正确实现参考如下:
// content.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class ContentService { constructor( private http: HttpClient, private sanitizer: DomSanitizer ) {} get(path: string): Observable<SafeHtml> { // 必须指定responseType为text,否则默认按JSON解析会报错 return this.http.get(path, { responseType: 'text' }).pipe( map(htmlContent => { // 将原始HTML内容转为Angular认可的安全HTML对象,避免XSS拦截 return this.sanitizer.bypassSecurityTrustHtml(htmlContent); }) ); } }
2. 修正静态HTML文件存放路径与引用路径
Angular打包时只会将src/assets目录下的静态资源原样输出,你需要:
- 将所有需要加载的HTML文件放到
src/assets/html/目录下(没有则手动创建) - 修改JSON文件中的content路径为绝对路径,示例如下:
[ { "heading": "Waswas", "content": "/assets/html/waswas.html" }, { "heading": "Flu", "content":"" } ]
注:确认
angular.json中projects -> 你的项目名 -> architect -> build -> options -> assets配置包含"src/assets",默认项目都会自带该配置。
3. 优化组件调用逻辑(可选,避免性能问题)
不要在模板中直接调用getContent方法,Angular变更检测会反复触发该方法,产生大量重复请求。建议在ngOnInit中预先加载内容:
// treatment.component.ts 新增逻辑 public treatmentContents: {heading: string, content?: SafeHtml}[] = []; ngOnInit(): void { this.treatmentsList.forEach(item => { if (item.content) { this.getContent(item.content).subscribe(html => { this.treatmentContents.push({ heading: item.heading, content: html }); }); } }); }
模板直接遍历预加载的数组即可:
<div *ngFor="let item of treatmentContents"> <h1>{{item.heading}}</h1> <span [innerHTML]="item.content"></span> </div>
内容的提问来源于stack exchange,提问作者M. Yusuf Suleman
相关产品推荐
相关产品推荐

