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:

  1. 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)
  2. 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, then src="" instead of null, which is valid HTML and wont throw a reference error)

Hope this helps!

Leave a Comment