【问题标题】:Show default image in Angular2在 Angular2 中显示默认图像
【发布时间】:2018-05-07 18:02:00
【问题描述】:

这是我的 html 文件中的内容:

<img src="{{( REST_URL + userId) || this.defaultImage }}" height="200" />

REST_URL 是用户/(在浏览器调用http://localhost:8080/user/123456 显示用户图像)

在我的component.ts文件中变量定义如下:

readonly REST_URL = 'user/';
userId: number;

并非所有用户都有图像,我希望在用户没有图像但它不起作用时显示默认图像......有什么想法吗?

【问题讨论】:

  • 仅供参考,模板中的所有内容都被假定为 this 的一部分,因此您无需在变量名前面加上它。

标签: html angular rest typescript spring-boot


【解决方案1】:

应该只是defaultImage

<img src="{{( REST_URL) || defaultImage }}" height="200" />

【讨论】:

【解决方案2】:

没有this,一个干净的方式:

<img [src]="REST_URL || defaultImage" height="200" />

【讨论】:

  • @Anarkie url 图片.../img.png 的其余部分在哪里?
  • REST_URL 是一个没有 /img.png 的休息调用
  • defaultImage的内容是什么,用户头像在哪里?
【解决方案3】:

以角度显示默认图像

REST_URL = `user/${this.userId}`;
this.restUrl = REST_URL || defaultImage;
<img [src]="restUrl" height="200" />

【讨论】:

  • this.restUrl String 的类型?
【解决方案4】:

正如其他答案中提到的,在引用组件类成员时,您不需要在模板中指定this。您的代码中还有另一个问题...

您假设,如果用户图像不存在,则将使用默认图像作为以下表达式的结果:

(REST_URL + userId) || defaultImage

但该表达式永远不会计算为defaultImage,因为(REST_URL + userId) 永远不会是falsy。即使图像不存在,其 URL 也不为空、未定义或为空。因此,始终使用用户图像 URL。


解决方案 1

如果你有一个标志来指示用户图像是否存在,你可以使用这样的代码:

<img [src]="imageExists ? REST_URL + userId : defaultImage" height="200" />

解决方案 2

另一种解决方案是处理error事件,如果无法加载用户图像,则将URL更改为默认图像:

<img [src]="imageUrl" height="200" (error)="onError()" />
private defaultImage = "http://www.yourWebSite.com/yourDefaultImage.jpg";

public imageUrl = REST_URL + this.userId;

public onError(): void {
    this.imageUrl = this.defaultImage;
}

您可以尝试this plunker中的代码。运行后看到“用户图片”,可以将代码中的userImage弄错,看到显示的是“默认图片”。

【讨论】:

    猜你喜欢
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 2019-06-13
    相关资源
    最近更新 更多