The following service method returns an image (if one exists for the given parameter in the database) or a 404 error if the image does not exist:
public getLegendImage(id: string): Observable<Blob> {
let params = new HttpParams();
params = params.append('id', id);
return <Observable<Blob>>this.http.get('service/getLegendImage', { params: params, responseType: 'blob'});
}
In my component I'm consuming it with an async pipe:
ngOnInit() {
this.data = this.activeLayers.map(layer => ({ id: layer.id, name: layer.name, image$: this.getLayerImage$(layer.id)}));
}
public getLayerImage$(layer: string): Observable<SafeUrl> {
return this.layerService.getLegendImage(layer).map(blob => this.domSanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(blob)))
.catch(err => Observable.of(-1));
}
And in the template:
<div *ngFor="let layer of this.data">
<b>{{ layer.name }}</b><br>
<span class="legend-image"><img [attr.src]="(layer.image$ | async)" /></span>
</div>
However, I'm still getting uncaught 404 http exceptions when the webservice request return 404.
If I return "undefined" in the .catch() method, I get the following error:
You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
The desired behaviour would be, that the image$ observable points to some default image in the assets of the client app if the service returns a 404 error. But I do not see how to do that :(
catchblock, instead of returning -1 or null or undefined, you return an Observable of that image path. - SiddAjmera