0

在这个 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"
4

1 回答 1

0

你可以这样做

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>
于 2020-12-12T10:41:16.340 回答