使用InnerHTML中的HTML Link在Angular中显示该文件



我希望像这样显示存储在json文件中的链接:

[
{
"heading": "Waswas",
"content": "./waswas.html"
},
{
"heading": "Flu",
"content":""
}
]

在我的组件中。我将其解析为一个数组变量,如下所示:

public treatmentsList:{heading: string, content: string}[] = treatments;

然后在我的component.html文件中添加如下内容:

<div>
<h1>
{{treatmentsList[0].heading}}
</h1>
<span [innerHTML]="getContent(treatmentsList[0].content) | async"></span>
</div>

但是它显示的是链接而不是文件

组件。ts文件:

import { Content } from '@angular/compiler/src/render3/r3_ast';
import { Component, NgModule, OnInit } from '@angular/core';
import { SafeHtml } from '@angular/platform-browser';
import { Observable } from 'rxjs';
import { ContentService } from '../content.service';
import treatments from "./treatments.json"
var heading = "hTempl"
@Component({
selector: 'app-treatment',
templateUrl: './treatment.component.html',
styleUrls: ['./treatment.component.css']
})
export class TreatmentComponent implements OnInit {
public treatmentsList:{heading: string, content: string}[] = treatments;

constructor(
private readonly contentService: ContentService
)  {}
public getContent(path: string): Observable<SafeHtml> {
return this.contentService.get(path);
}
ngOnInit(): void {
}
}

app.module.ts:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { TreatmentComponent } from './treatment/treatment.component';
import { PrgrefComponent } from './prgref/prgref.component';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent,
TreatmentComponent,
PrgrefComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

创建一个服务来获取html文档,然后对它们进行消毒。

content.service.ts

import { HttpClient, HttpHeaders  } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root',
})
export class ContentService {
constructor(
private readonly http: HttpClient,
private readonly sanitizer: DomSanitizer
) {}
public get(path: string): Observable<SafeHtml> {
const headers = new HttpHeaders({
'Content-Type':  'text/plain',
});
return this.http.get(path, {
headers,
responseType: 'text'
}).pipe(
// This is unsafe if the path and content is not under your control
map(html => this.sanitizer.bypassSecurityTrustHtml(html))
);
}
}

然后在你的组件中。使用服务

constructor(
private readonly contentService: ContentService
)
public getContent(path: string): Observable<SafeHtml> {
return this.contentService.get(path);
}
最后你的html
<span [InnerHTML]="getContent(treatmentsList[0].content) | async"></span>

最新更新