Nic Gibson Nic Gibson - 26 days ago 11
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

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);
}
}

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.