Angular async pipe does not work for image source update

1.3k views Asked by At

in this Angular component, I get an observable of user object, I try to verify on NgInit, whether the profile picture URL is defined. If not, I want to set a placeholder for that. But for some reason, the change I make within ngOnInit is too late. The image source is not set properly, so the result is the alternative text is being displayed. I thought the async pipe will help me to get the image whenever it is newly set? Could someone help me to get a better understanding for this context? :)

  @Input()
  user$: Observable<UserProfileData>;

  userSub: Subscription;

  constructor() { }

  ngOnDestroy(): void {
    this.userSub.unsubscribe();
  }

  ngOnInit(): void {
    this.userSub = this.user$.subscribe(user=> {
      user.profilePictureUrl = (user.profilePictureUrl) ? user.profilePictureUrl : '/assets/placeholder.png';
      }
    )
  }

And in HTML, I simply call the user profile picture with async pipe.

<img class="ml-lg-5 mb-2 mb-md-0 mx-auto rounded-circle" src="{{(user$|async).profilePictureUrl}}" alt="{{ (user$|async).username }}">

This is what I get for user$, it is from an object of UserProfileData:

description: "My name is Steve, I look forward to collaborating with you guys!"
firstname: "Steve"
lastname: "Mustermann"
location: LocationModel {country: "Germany", city: "Hamburg", zipcode: "22145"}
occupation: "Barber"
profilePictureUrl: ""
score: "69.1"
username: "steve669"
1

There are 1 answers

2
Hoang NK On BEST ANSWER

You can do it like this

ngOnInit(): void {
  this.user$ = this.user$.pipe(map(user => {
    if (!user.profilePictureUrl) {
      user.profilePictureUrl = '/assets/placeholder.png';
    }

    return user;
  }));
)

In the template

<ng-container *ngIf="user$ | async as user">
  <img class="ml-lg-5 mb-2 mb-md-0 mx-auto rounded-circle" src="{{user.profilePictureUrl}}" alt="{{ user.username }}">
</ng-container>