如何检查 url 中的图像是否已损坏

how to check if images from url is broken

我正在处理 ionic 4 项目。我的项目正在从 url 获取数据 json 。我想检查来自 url 的图像是否已损坏。如果坏了显示另一个图像。我尝试了不同的代码,但没有人在工作。

我使用的代码是

   <ion-row *ngFor="let item of items" justify-content-around test-center>


          <ion-col >
              <img src="/images/data/operators/{{item.flight.airline.code.icao}}_logo0.png"  onerror="this.src='images/data/operators/{{item.flight.airline.code.iata}}_{{item.flight.airline.code.icao}}.png'">

          </ion-col>


        </ion-row>

我在 运行

时出错
ERROR Error: Uncaught (in promise): Error: Template parse errors:
Binding to event property 'onerror' is disallowed for security reasons, please use (error)=...
If 'onerror' is a directive input, make sure the directive is imported by the current module.

取决于错误如果我使用 (error)= 我得到另一个错误是

ERROR Error: Uncaught (in promise): Error: Template parse errors:
Parser Error: Got interpolation ({{}}) where expression was expected at column 69 in [this.src=

有什么解决办法吗?

(error) 捕获由 img 触发的错误事件。使用类似:

<img src="..." (error)="handleImgError($event, item)">

在您的组件中创建函数 handleImgError()

function handleImgError(ev: any, item : any){
   let source = ev.srcElement;
   let imgSrc = `images/data/operators/${item.flight.airline.code.iata}_${item.flight.airline.code.icao}.png`;

   source.src = imgSrc;

}

你应该试试这个。如果找不到图像,它将加载替代图像

 <img   class="img-style"  [src]="user.photo ? user.photo : 'https://images.vexels.com/media/users/3/145908/preview2/52eabf633ca6414e60a7677b0b917d92-male-avatar-maker.jpg'">