这就是我在html文件中的内容:
<img src="{{( REST_URL + userId) || this.defaultImage }}" height="200" />
REST_URL是user /(在浏览器调用http://localhost:8080/user/123456上显示用户图像)
在我的component.ts文件变量中定义如下:
readonly REST_URL = 'user/';
userId: number;
并非所有用户都有图片,我希望在用户没有图片时显示默认图片,但它不起作用......任何想法?
答案 0 :(得分:2)
应该只是 defaultImage
<img src="{{( REST_URL) || defaultImage }}" height="200" />
答案 1 :(得分:2)
没有this
,一个干净的方式:
<img [src]="REST_URL || defaultImage" height="200" />
答案 2 :(得分:1)
以角度
显示默认图像REST_URL = `user/${this.userId}`;
this.restUrl = REST_URL || defaultImage;
<img [src]="restUrl" height="200" />
答案 3 :(得分:0)
正如其他答案所述,在引用组件类成员时,您不需要在模板中指定this
。你的代码中还有另一个问题......
您认为,如果用户图像不存在,则默认图像将用作以下表达式的结果:
(REST_URL + userId) || defaultImage
但该表达式永远不会评估为defaultImage
,因为(REST_URL + userId)
永远不会falsy。即使图像不存在,其URL也不是null,未定义或为空。因此,始终使用用户图像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中的代码。运行它并看到&#34;用户图像&#34;后,您可以在代码中使userImage
不正确,并看到&#34;默认图像&#34;显示。