简体   繁体   English

在Angular2中显示默认图像

[英]Show default image in Angular2

This is what I have in my html file: 这就是我的html文件中的内容:

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

REST_URL is user/ (on browser call http://localhost:8080/user/123456 shows user image) REST_URL是用户/(在浏览器上调用http:// localhost:8080 / user / 123456显示用户图像)

in my component.ts file variables are defined as below: 在我的component.ts文件中,变量定义如下:

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

Not all users have an image and I expect default image to be shown when the user doesn't have an image but it doesn't work... any ideas? 并非所有用户都有图像,我希望当用户没有图像但无法正常工作时显示默认图像...有什么想法吗?

它应该只是defaultImage

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

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

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

showing default image in angular 以角度显示默认图像

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

As mentioned in other answers, you don't need to specify this in your template when referring to the component class members. 如其他答案中所述,在引用组件类成员时,无需在模板中指定this内容。 And there is another problem in your code... 您的代码中还有另一个问题...

You assume that, if the user image doesn't exist, the default image will be used as a result of the following expression: 您假设,如果用户图像不存在,则由于以下表达式,将使用默认图像:

(REST_URL + userId) || defaultImage

But that expression will never evaluate to defaultImage because (REST_URL + userId) is never falsy . 但是该表达式永远不会评估为defaultImage因为(REST_URL + userId)永远不会伪造 Even if the image doesn't exist, its URL is not null, undefined or empty. 即使图像不存在,其URL也不为null,未定义或为空。 Therefore, the user image URL is always used. 因此,始终使用用户图像URL。


Solution 1 解决方案1

If you have a flag that indicates if the user image exists or not, you can use code like this: 如果您有一个标志指示用户图像是否存在,则可以使用如下代码:

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

Solution 2 解决方案2

Another solution is to handle the error event and to change the URL to the default image if the user image cannot be loaded: 另一个解决方案是处理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;
}

You can try the code in this plunker . 您可以在此插件中尝试代码。 After running it and seeing the "user image", you can make userImage incorrect in the code and see that the "default image" is displayed. 运行它并看到“用户图像”后,可以在代码中使userImage错误,并看到显示了“默认图像”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM