Search code examples
angularangular7

Check if Observable is undefined


On an Angular 7 application I have the following template:

<div *ngIf="avatarUrl$ | async;">
  <ng-container *ngIf="avatarUrl$ | async as avatarUrl">
    <img [src]="avatarUrl ? avatarUrl : 'avatar-default.png'">
  </ng-container>
</div>

The avatarUrl$ is an observable as is obtained from a database through a service.

I want to display the IMG only after avatarUrl$ has a value loaded.

However, sometimes that value obtained from the service is undefined.

In that case I need to display the default avatar, e.g: avatar-default.png.

The problem is that avatar-default.png is not displayed when avatarUrl$ is undefined.

I think because of this condition that does not differentiate from the value not being loaded and being loaded but is undefined?

<div *ngIf="avatarUrl$ | async;">

How can I solve this?


Solution

  • You can achieve that with object of observable. It is usefull when you want the value null, undefined or 0 from your observable not to be blocked in the *ngIf

    <div *ngIf="{url: avatarUrl$ | async} as data">
        <img [src]="data.url ? data.url : 'avatar-default.png'">
    </div>
    

    It's good to know, that you can have multiple observables in your object if you want:

    <div *ngIf="{url: avatarUrl$ | async, picture: pictureUrl$ | async} as data">
    ...
    </div>