I'm trying to retrieve HTML from a REST service and display it using Angular (4.3). I can watch the service get called and return the correct content. However, the angular component using this never seems to actually receive the content. What have I missed?
Specifically a console.log(html)
(in the second code sample below) always outputs null.
I have an angular service that looks like:
@Injectable()
export class SlidesService {
private requestUrl: string;
constructor(
@Inject(AppConfig) private config: AppConfig,
@Inject(HttpClient) private http: HttpClient) {
this.requestUrl = this.config.restRoot + listSlidesUrl;
}
getSlide(deck: string, slide: string): Observable<string> {
const headers: HttpHeaders = new HttpHeaders({'Accept': 'text/html'});
const thisUrl: string = this.requestUrl + '/' + deck + '/' + slide;
return this.http.get<string>(thisUrl, { headers: headers });
}
}
This is used by a component:
export class SlidePreviewComponent implements OnInit {
@Input() slide: string; /* Identifier for the slide */
@Input() deck: string;
slideHtml: string;
constructor(private slideService: SlidesService) {
}
ngOnInit(): void {
this.slideService.getSlide(this.deck, this.slide)
.subscribe(html => this.setSlideHtml(html) );
}
setSlideHtml(html: string) {
this.slideHtml = html;
console.log(html);
}
}
If the HTML value contains a <script> tag, Angular by default will not render it as HTML. If you attempt to render a <script> tag through interpolation ({{ & }}), Angular will render the value as text.
If you want to show the HTML code, you could use [innerText] instead, or simply use string interpolation as @Vega noted. That will properly escape the HTML. Binding to [innerText] will preserve the line breaks.
AngularJS is a JavaScript framework. It can be added to an HTML page with a <script> tag.
You can place those files under src/assets folder and specify the path in angular. json . Meaning, you can keep the files to be included under src/assets/html and src/assets/js folders. angular.
The new HttpClient class expects the get()
method to return JSON response. If you expect a text (HTML), it's necessary to specify it in the request options:
this.http.get(thisUrl, { headers: headers, responseType: 'text' });
The special Accept
header may be unnecessary then.
Hi can you try this in service
getSlide(deck: string, slide: string){
const thisUrl: string = this.requestUrl + '/' + deck + '/' + slide;
return this.http
.get(url ,{ headers: headers, responseType: 'text' })
.toPromise()
.then(resp => resp.text())
.catch(error=>console.log(error))
}
and your component
ngOnInit(): void {
this.slideService.getSlide(this.deck, this.slide)
.subscribe(html => this.setSlideHtml(html) );
}
setSlideHtml(html) {
this.slideHtml = html;
console.log(html);
}
in your template
<div id="scroll" [innerHTML]="slideHtml"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With