Skip to content

Commit

Permalink
fix: on image load rate the 204 as error to display placeholder (#606)
Browse files Browse the repository at this point in the history
  • Loading branch information
HenryT-CG authored Nov 14, 2024
1 parent fb3c747 commit 3129dd5
Showing 1 changed file with 27 additions and 14 deletions.
41 changes: 27 additions & 14 deletions libs/angular-accelerator/src/lib/directives/src.directive.ts
Original file line number Diff line number Diff line change
@@ -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]' })
Expand All @@ -13,37 +13,50 @@ 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<Blob>) => {
// 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'
}
this._src = value
}
}

constructor(private el: ElementRef, private httpClient: HttpClient) {
constructor(
private el: ElementRef,
private httpClient: HttpClient
) {
this.el.nativeElement.style.visibility = 'hidden'
}
}

0 comments on commit 3129dd5

Please sign in to comment.