GET http://localhost:4200/null 404 (Not Found) in angular2 with angular-cli
So I just had an exhausting time figuring this out, but I did.
This happened to me right after doing an update as well but it had nothing to do with that.
It's definitely from a reference to a variable with a null value and it's most likely an image src attribute. At least it was for me and I'm using values from a server all over the place in my app and img
src were the only things causing this and it makes sense.
I had something similar to this:
<img [src]="myData?.imageUrl">
I thought that the ?
safe operator would make sure I didn't get null errors, which it generally does but it seems like when you bind to a src
attribute, the browser throws an error, not the compiler. The compiler lets you bind null to it because of the safe operator, but because src
is a reference URL, the browser is still looking for that URL and the console throws the error because it can't find the URL relative/app/path/null
The two ways I found to solve this:
- Use ngIf:
<img *ngIf="myData" [src]="myData.imageUrl"/>
(entire image and its src attribute never even get loaded if theres no data, avoiding the issue entirely) - Use interpolation:
<img src="{{ myData?.imageUrl }}"/>
(NOTICE in this solution you still need the safe operator because the compiler will throw an error otherwise, as expected, but now if the value is null, thensrc=""
instead of null, which is valid HTML and wont throw a reference error)
Hope this helps!
What's happening is that some browsers (i.e. Chrome) perform some toString
function on the src
attribute, which causes null
to become 'null'
instead of ''
, thus triggering to the browser to look for //domain.com/null
.
Some may remember ng-src
from AngularJS, which was created to handle this.
Anyway, after trying a lot of options, I found the solutions to be:
<img [attr.src]="myImageUrl"/>
It works for async
too (which was mainly causing this problem for me):
<img [attr.src]="myImageUrl | async"/>
This works because instead of setting src
to either 'null'
or ''
, the src attribute isn't set at all as long as the variable/path used is not set/resolved, therefor not triggering the error.
An addition to HauntedSmores answer: you can also use a ''
-fallback:
[src]="myObj.img || ''"
since the elvis-operator ?
is not available in .ts-files, but only in templates, you can also put this into typescript-getters.