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



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

最新更新