Nic Gibson Nic Gibson - 6 months ago 64
HTML Question

Retrieve html from server and display with Angular

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

(in the second code sample below) always outputs null.

I have an angular service that looks like:

export class SlidesService {

private requestUrl: string;

@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;

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download