From 3129dd52d5eca454646df5b5ee9b997e0916137e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henry=20T=C3=A4schner?= <129834483+HenryT-CG@users.noreply.github.com> Date: Thu, 14 Nov 2024 12:21:57 +0100 Subject: [PATCH] fix: on image load rate the 204 as error to display placeholder (#606) --- .../src/lib/directives/src.directive.ts | 41 ++++++++++++------- 1 file changed, 27 insertions(+), 14 deletions(-) diff --git a/libs/angular-accelerator/src/lib/directives/src.directive.ts b/libs/angular-accelerator/src/lib/directives/src.directive.ts index 4599294a..da3be811 100644 --- a/libs/angular-accelerator/src/lib/directives/src.directive.ts +++ b/libs/angular-accelerator/src/lib/directives/src.directive.ts @@ -1,4 +1,4 @@ -import { HttpClient } from '@angular/common/http' +import { HttpClient, HttpResponse } from '@angular/common/http' import { Directive, ElementRef, EventEmitter, Input, Output } from '@angular/core' @Directive({ selector: '[ocxSrc]' }) @@ -13,29 +13,39 @@ export class SrcDirective { return this._src } set ocxSrc(value: string | undefined) { - if (value && this._src !== value) { + if (value && this._src !== value && window.location.hostname) { try { if (new URL(value, window.location.origin).hostname === window.location.hostname) { - this.httpClient.get(value, { responseType: 'blob' }).subscribe({ - next: (blob) => { - const url = URL.createObjectURL(blob) - this.el.nativeElement.onload = () => { - URL.revokeObjectURL(url) + this.httpClient.get(value, { observe: 'response', responseType: 'blob' }).subscribe( + (response: HttpResponse) => { + // ok with content + if (response?.status === 200) { + const url = URL.createObjectURL(response.body as Blob) + this.el.nativeElement.onload = () => { + URL.revokeObjectURL(url) + } + this.el.nativeElement.src = url + } + // no content + if (response?.status === 204) { + this.error.emit() } - this.el.nativeElement.src = url - this.el.nativeElement.style.visibility = 'initial' }, - error: () => { + () => { + // on error this.error.emit() - this.el.nativeElement.style.visibility = 'initial' }, - }) + () => { + // on complete + this.el.nativeElement.style.visibility = 'initial' + } + ) } else { this.el.nativeElement.src = value this.el.nativeElement.style.visibility = 'initial' } } catch (error) { - console.log('Cannot parse URL ', value, error) + console.error('Cannot parse URL ', value, error) this.el.nativeElement.src = value this.el.nativeElement.style.visibility = 'initial' } @@ -43,7 +53,10 @@ export class SrcDirective { } } - constructor(private el: ElementRef, private httpClient: HttpClient) { + constructor( + private el: ElementRef, + private httpClient: HttpClient + ) { this.el.nativeElement.style.visibility = 'hidden' } }