Angular 异步管道不适用于图像源更新

Angular async pipe does not work for image source update

在这个 Angular 组件中,我得到了一个用户对象的可观察对象,我尝试在 NgInit 上验证是否定义了个人资料图片 URL。如果没有,我想为此设置一个占位符。但出于某种原因,我在 ngOnInit 中所做的更改为时已晚。图片来源设置不当,导致显示的是替代文字。我认为异步管道会帮助我在新设置时获取图像?有人可以帮助我更好地理解这种情况吗? :)

  @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';
      }
    )
  }

而在HTML中,我只是用异步管道调用用户头像。

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

这是我为 user$ 得到的,它来自 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"

你可以这样做

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

    return user;
  }));
)

在模板中

<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>