Angular universal / ng-toolkit/universal throws error when image doesn't exist

Viewed 581

I'm using @ng-toolkit/universal for my server-side rendering approach. Everything works fine, without my images. I'm getting them dynamically. So when a user doesn't have an Avatar, there is a placeholder image which gets shown. Therefore I'm using this function:

verifyAvatar(imageSrc) {
        let img = new Image;
        img.src = imageSrc;

        if(img.complete){
            this.userAvatar= imageSrc
        } else {
            this.userAvatar= '../../../../assets/images/userGraphics/no_avatar.png';
        }
    }

But this function gives ma an error inside my server.ts / logfile ->

ERROR { Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'assets/images/userGraphics/5c38f71e07b6b83f20b46993_avatar' Error: Cannot match any routes. URL Segment: 'assets/images/userGraphics/5c38f71e07b6b83f20b46993_avatar'

The full error for two images is about 300 - 450 lines long. I hope you understand, that you get confused when your server console is flooded with this.

So how do I deal with Angular universal/Ng-toolkit/universal, so that there is no error thrown?

Just for notification, my function works fine and my server doesn't crash, but I would feel much better when the error is gone.

Edit: I just created a repo to reproduce this -> https://github.com/Sanafan/angularUniversalTest

the error is also thrown when an image is defined: enter image description here

2 Answers

Since angular reply with an error with a md5sum hash, This means there is a setting problem to recognize it as a png file.

What happens, if you replace your component HTML has followed (set userAvatarSrc to false when undefined)?

<div  *ngIf="userAvatarSrc">
<img [src]="userAvatarSrc"></img>
</div> 
<div  *ngIf="!userAvatarSrc">
<img src="../../assets/images/userGraphics/noAvatar.png"></img>
</div> 

I haven't used Angular Universal much, but, as far as I have read/known, you are setting dist/browser folder as a static resource in express server.

Now, in your verifyAvatar function, you are creating an HTMLImageElement (new Image), and assigning src in the very next line.

So, the server will try to create an Image element, with provided src value. In your case, it won't find any image at a given path (src) and will log errors.

After above, it will continue to check the angular condition (if (img.complete)), which will be false and the correct path will be assigned to userAvatar variable. And you would see correct image in the browser.

So, the errors which you are seeing in a terminal window (at server-side), are coming because you are trying to create Image element with the path, which does not have any image.

To avoid this, you must check image existence at server-side only.

Related