角度2-检查图片网址是否有效或损坏


76

我正在从API提取大量图像URL,并将它们显示在angular 2 Web应用程序中。一些网址已损坏,我想用存储在本地Web服务器上的默认图片替换它们。有没有人建议如何测试网址,并且在状态码404的情况下替换损坏的图片?

谢谢!

Answers:


156

监听error图像元素的事件:

<img [src]="someUrl" (error)="updateUrl($event)">

updateUrl(event) { ... }分配一个新值this.someUrl

柱塞示例

如果只想检入代码,则可以使用javascript检查图像是否存在中所述的方法。

@Directive({
  selector: 'img[default]',
  host: {
    '(error)':'updateUrl()',
    '[src]':'src'
   }
})
class DefaultImage {
  @Input() src:string;
  @Input() default:string;

  updateUrl() {
    this.src = this.default;
  }
}

指令柱塞示例


2
为什么这个被否决?AFAIK,这是利用浏览器事件的正确方法...
Cory Silva

@GünterZöchbauer最好有指示来处理这样的事情。有什么想法吗?+1
Pankaj Parkar '16

你是对的。我以某种方式错过了“默认图片”,并进行了一些计算以获得备用URL。
君特Zöchbauer

在指令中将默认图像指定为类属性会更好吗?如果我错过[default]='...'图像中的a ,我将跳过它,并且您避免default在每个<img>标签中添加。
埃里克·马丁内斯

2
谢谢,它为我解决了IIS相对路径问题。乌达老板!
Jaime Yule's

51

您可以通过onError这种方式使用事件来处理invalid urlbroken url

<img [src]="invalidPath" onError="this.src='images/angular.png'"/> 

这样您可以通过onError事件将img路径直接分配给src


2
至少检查活塞。我认为不是正确的还是不正确的。关于其他方式....你怎么说?
micronyks '16

2
不,我没有把它弄错,别担心。只是说也可以有其他选择。这就是其中之一。这样,您可以直接分配路径。
micronyks '16

1
感谢@PankajParkar
micronyks '16

1
在Angular 6上工作正常
Celso Soares

1
适用于Angular 8和9。感谢@micronyks。👍
AllJs

23

我关于角度4的示例

<img [src]="img" (error)="img.src = errorImg" #img>
  1. 其中img-图片路径;
  2. 错误-错误发出
  3. errorImg-默认img的路径
  4. #img-链接到img对象

它这样做最彻底的方法,工作没有任何问题
罗密·戈梅斯

在ngFor中有图片标记的情况下,如何使#img链接(以及错误处理程序中的img参考)动态化?
HisDivineShadow

我对这个答案一视同仁,因为它起初似乎很有效,然后我注意到,即使所有资产和图像均已正确加载,浏览器仍会永久加载(在Chrome的标签中加载微调框)。它可以工作,但是存在一个烦人的无限加载问题。不过,直到问题被编辑后,才能撤消我的投票。
杰里米·锡耶

7

我找到了一个对我有用的非常简单的解决方案。这不会检查404,但是我有可能具有和.image属性的对象。我知道这不是他的问题的答案,但希望它能帮助一些人。

<img class="list-thumb-img" [attr.src]="item.image?.url ? item.image.url : 'assets/img/140-100.png'">

是。这是最简单的解决方案。感谢
Abhiz '19

7

我使用base64加载微调器:

<img [src]="photoContainer.photo.url | secure" onError="this.src='data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBzdGFuZGFsb25lPSJubyI/Pgo8IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4iICJodHRwOi8vd3d3LnczLm9yZy9HcmFwaGljcy9TVkcvMS4xL0RURC9zdmcxMS5kdGQiPgo8c3ZnIHdpZHRoPSI0MHB4IiBoZWlnaHQ9IjQwcHgiIHZpZXdCb3g9IjAgMCA0MCA0MCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4bWw6c3BhY2U9InByZXNlcnZlIiBzdHlsZT0iZmlsbC1ydWxlOmV2ZW5vZGQ7Y2xpcC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlLWxpbmVqb2luOnJvdW5kO3N0cm9rZS1taXRlcmxpbWl0OjEuNDE0MjE7IiB4PSIwcHgiIHk9IjBweCI+CiAgICA8ZGVmcz4KICAgICAgICA8c3R5bGUgdHlwZT0idGV4dC9jc3MiPjwhW0NEQVRBWwogICAgICAgICAgICBALXdlYmtpdC1rZXlmcmFtZXMgc3BpbiB7CiAgICAgICAgICAgICAgZnJvbSB7CiAgICAgICAgICAgICAgICAtd2Via2l0LXRyYW5zZm9ybTogcm90YXRlKDBkZWcpCiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIHRvIHsKICAgICAgICAgICAgICAgIC13ZWJraXQtdHJhbnNmb3JtOiByb3RhdGUoLTM1OWRlZykKICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICAgICAgQGtleWZyYW1lcyBzcGluIHsKICAgICAgICAgICAgICBmcm9tIHsKICAgICAgICAgICAgICAgIHRyYW5zZm9ybTogcm90YXRlKDBkZWcpCiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIHRvIHsKICAgICAgICAgICAgICAgIHRyYW5zZm9ybTogcm90YXRlKC0zNTlkZWcpCiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICAgIHN2ZyB7CiAgICAgICAgICAgICAgICAtd2Via2l0LXRyYW5zZm9ybS1vcmlnaW46IDUwJSA1MCU7CiAgICAgICAgICAgICAgICAtd2Via2l0LWFuaW1hdGlvbjogc3BpbiAxLjVzIGxpbmVhciBpbmZpbml0ZTsKICAgICAgICAgICAgICAgIC13ZWJraXQtYmFja2ZhY2UtdmlzaWJpbGl0eTogaGlkZGVuOwogICAgICAgICAgICAgICAgYW5pbWF0aW9uOiBzcGluIDEuNXMgbGluZWFyIGluZmluaXRlOwogICAgICAgICAgICB9CiAgICAgICAgXV0+PC9zdHlsZT4KICAgIDwvZGVmcz4KICAgIDxnIGlkPSJvdXRlciI+CiAgICAgICAgPGc+CiAgICAgICAgICAgIDxwYXRoIGQ9Ik0yMCwwQzIyLjIwNTgsMCAyMy45OTM5LDEuNzg4MTMgMjMuOTkzOSwzLjk5MzlDMjMuOTkzOSw2LjE5OTY4IDIyLjIwNTgsNy45ODc4MSAyMCw3Ljk4NzgxQzE3Ljc5NDIsNy45ODc4MSAxNi4wMDYxLDYuMTk5NjggMTYuMDA2MSwzLjk5MzlDMTYuMDA2MSwxLjc4ODEzIDE3Ljc5NDIsMCAyM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wxNy43OTQyIDMzLjgwMDMsMTYuMDA2MSAzNi4wMDYxLDE2LjAwNjFaIiBzdHlsZT0iZmlsbDpyZ2IoNzQsNzQsNzQpOyIvPgogICAgICAgIDwvZz4KICAgICAgICA8Zz4KICAgICAgICAgICAgPHBhdGggZD0iTTI4LjQ5MzksNS44NTc4NkMzMC4wNTM2LDQuMjk4MTUgMzIuNTgyNCw0LjI5ODE1IDM0LjE0MjEsNS44NTc4NkMzNS43MDE5LDcuNDE3NTggMzUuNzAxOSw5Ljk0NjM4IDM0LjE0MjEsMTEuNTA2MUMzMi41ODI0LDEzLjA2NTggMzAuMDUzNiwxMy4wNjU4IDI4LjQ5MzksMTEuNTA2MUMyNi45MzQyLDkuOTQ2MzggMjYuOTM0Miw3LjQxNzU4IDI4LjQ5MzksNS44NTc4NloiIHN0eWxlPSJmaWxsOnJnYig1MCw1MCw1MCk7Ii8+CiAgICAgICAgPC9nPgogICAgPC9nPgo8L3N2Zz4K'">

4

完美的Angular 8指令:

import {AfterViewInit, Directive, ElementRef, Input} from '@angular/core';

@Directive({
    selector: '[appImage]'
})
export class ImageDirective implements AfterViewInit {

    @Input() src;

    constructor(private imageRef: ElementRef) {
    }

    ngAfterViewInit(): void {
        const img = new Image();
        img.onload = () => {
            this.setImage(this.src);
        };

        img.onerror = () => {
            // Set a placeholder image 
            this.setImage('assets/placeholder.png');
        };

        img.src = this.src;
    }

    private setImage(src: string) {
        this.imageRef.nativeElement.setAttribute('src', src);
    }
}

现在,HTML将是:

<img [src]="'/some/valid-image.png'" appImage>

它没有应用指令。我创建了指令,但没有用!
Pathik Vejani

3

如果要更改未加载的图像或源已损坏... Angular 8,只需更改此目标的默认资源的src:

  • 组件HTML

    <... [src] =“ person.pictureUrl”(错误)=“ pictNotLoading($ event)”>

  • 组件TS

    pictNotLoading(event){event.target.src ='assets / nopicture.png'; }


2

这是我针对多图像后备的解决方案。一旦解决了图像,我们基本上就分离了ChangeDetector,因此一旦解决了图像,我们就可以减少vm检查周期上的CPU。

import {Component, ChangeDetectionStrategy, ChangeDetectorRef} from 'angular2/core';
import {AppStore} from "angular2-redux-util/dist/index";



@Component({
    selector: 'logoCompany',
    changeDetection: ChangeDetectionStrategy.Default,
    template: `
            <div style="padding-top: 7px" > 
              <span style="color: gainsboro; font-family: Roboto">{{getBusinessInfo('companyName')}}</span>
              <!--<img style="width: 35px" class="img-circle" src="http://galaxy.example.me/Resources/Resellers/{{getBusinessInfo('businessId')}}/{{getBusinessInfo('fileName')}}" />-->
              <img style="width: 35px" class="img-circle" [src]="getImageUrl()" (load)="onImageLoaded()" (error)="onImageError()" />
            </div>
    `
})

export class LogoCompany {

    constructor(private cdr:ChangeDetectorRef) {    
    }
    private imageRetries:number = 0;
    private unsub;


    private detach() {
        this.cdr.detach();
    }

    private getImageUrl() {          
        var url = '';
        switch (this.imageRetries){
            case 0: {
                url = 'http://galaxy.example.me/Resources/Resellers/' + this.getBusinessInfo('businessId') + '/Logo.jpg'
                break;
            }
            case 1: {
                url = 'http://galaxy.example.me/Resources/Resellers/' + this.getBusinessInfo('businessId') + '/Logo.png'
                break;
            }
            default: {
                url = 'assets/person.png'
                break;
            }

        }
        return url;
    }

    private onImageLoaded() {
        this.detach();
    }

    private onImageError() {
        this.imageRetries++;
    }

    private getBusinessInfo(field):string {
          return '12345';
    }





}

0

您可以为此用例简单地使用三元运算符。我假设您正在从远程服务器获取响应

<img src="{{ res.image ? res.image : onErrorFunction() }}"

如果您不想从服务器获取图像,请在路径中用单引号''引起来。

在这里,如果链接断开,则将转到onErrorFunction;如果未断开,将加载res.image。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.