简体   繁体   English

Angular async pipe 不适用于镜像源更新

[英]Angular async pipe does not work for image source update

in this Angular component, I get an observable of user object, I try to verify on NgInit, whether the profile picture URL is defined.在这个 Angular 组件中,我得到了一个用户 object 的观察值,我尝试在 NgInit 上验证,是否定义了配置文件图片 URL。 If not, I want to set a placeholder for that.如果没有,我想为此设置一个占位符。 But for some reason, the change I make within ngOnInit is too late.但由于某种原因,我在 ngOnInit 中所做的更改为时已晚。 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?我认为异步 pipe 将帮助我在新设置时获取图像? 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.而在 HTML 中,我只需使用异步 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:这是我从user$得到的,它来自 UserProfileData 的 object:

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"

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM