E J*_*rod 4 rest url image angular
我需要知道如何使用 Angular 检测图像是否存在(仅在客户端)。我听说我们可以使用超时功能设置默认图像,但我不知道如何捕获 404 错误。
我只需要在 getResourceImg() 上编写代码,正如Angular 的风格指南所说
资源-ui.component.ts
@Input() resource: IResourcePublished;
// ...
resourceImgUrlLogoDefault: string = 'assets/images/logo_default.png';
resourceImgUrl: string;
constructor(private modalService: NgbModal) {}
ngOnInit(): void {
this.resourceImgUrl = this.getRessourceImg(this.resource);
}
getResourceImg(resource: IResourcePublished): string {
return 'assets/images/screen-resources/' + resource.id + '.png';
}
//..
Run Code Online (Sandbox Code Playgroud)
这是模板(用 生成*ngFor="let resource of resources"
):
资源-ui.component.html
@Input() resource: IResourcePublished;
// ...
resourceImgUrlLogoDefault: string = 'assets/images/logo_default.png';
resourceImgUrl: string;
constructor(private modalService: NgbModal) {}
ngOnInit(): void {
this.resourceImgUrl = this.getRessourceImg(this.resource);
}
getResourceImg(resource: IResourcePublished): string {
return 'assets/images/screen-resources/' + resource.id + '.png';
}
//..
Run Code Online (Sandbox Code Playgroud)
您可以创建可重用的指令,例如:
后备-img.directive.ts
import { Directive, Input, HostBinding, HostListener } from '@angular/core';
@Directive({
selector: 'img[fallback]'
})
export class FallbackImgDirective {
@Input()
@HostBinding('src')
src: string;
@Input() fallback: string;
@HostListener('error')
onError() {
this.src = this.fallback;
}
}
Run Code Online (Sandbox Code Playgroud)
用法
<img src="http://unknown/404.jpg" fallback="https://via.placeholder.com/150" alt="">
Run Code Online (Sandbox Code Playgroud)