【问题标题】:Angular async pipe does not work for image source update角度异步管道不适用于图像源更新
【发布时间】:2020-12-12 10:09:21
【问题描述】:

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

【问题讨论】:

  • 你为什么在组件和模板中都订阅 observable user$
  • 有没有办法只在一个地方订阅?随时与我分享您的方法:)
  • 是的。您可以选择在其中一个地方而不是两个地方都这样做。
  • 另外,可以分享一下user$订阅后返回的内容吗?
  • 如果我只想订阅组件,如何在模板中声明呢?

标签: angular typescript asynchronous observable async-pipe


【解决方案1】:

你可以这样做

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>

【讨论】:

  • 嗨!非常感谢您提供这个有效的解决方案!我已经读到 .subscribe() 不适用于 onPush 更改检测策略 ootb,但是如果我遵循订阅方法,我将如何使其也能正常工作?
  • `公共用户:UserProfileData; ngOnInit(): void { this.user$.subscribe((user => { if (!user.profilePictureUrl) { user.profilePictureUrl = '/assets/placeholder.png'; } this.user = user; })); ) ` 在模板中 ` `
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-26
  • 1970-01-01
  • 2021-10-12
  • 2021-02-02
  • 2019-12-27
  • 2020-07-27
  • 2016-06-01
相关资源
最近更新 更多