angular: [src] attribute the first time it calls to an undefined endpoint
GET http://localhost:8080/undefined 404 (Not Found)
<img [src]="data.avatar_url" width="100" height="100"/>
this.data = {};
http.get('https://api.github.com/users/danicomas').toRx().map(res => res.json()).subscribe(response => this.data = response);
About this issue
- Original URL
- State: closed
- Created 9 years ago
- Comments: 23 (15 by maintainers)
The solutions above did not work for me for this situation:
[src]='getImageUrl() | async'
before the promise is resolved, I have a momentarily null value that causes the request to be triggered anyway. The solution that worked for me and can easily cover the above scenarios too is:
[attr.src]='getImageUrl() | async'
I mentioned this subtlety in this issue https://github.com/angular/angular/issues/3007 (for me it was making
/null
requests) the current workaround is|| ''
soor default the initial
avatar_url
value to empty string (probably a good idea anyways).I would say if interpolation gets to have a default case of empty string then
[src]
should as well. Here’s my codeSo, I’ve just tested how this behaves in Chrome without Angular. Executing this code in the console:
So, looking at the above it seems like browsers (or at least Chrome) will do “to string” conversion for
null
\undefined
. Now, I find this behavior debatable, maybe it makes sense to file an issue for this?In any case the work-around is simple: initialize data with an empty string (
this.data = {avatar_url: ''};
) or write a custom pipe to do null / undefined to string conversion (<img [src]="data.avatar_url | tostring"
) or just use a conditional exp:<img [src]="data.avatar_url ? data.avatar_url : ''">