gpt4 book ai didi

typescript - 在等待来自服务的异步/REST 数据时防止错误呈现到 View - RxJS/Angular2

转载 作者:太空狗 更新时间:2023-10-29 18:34:50 27 4
gpt4 key购买 nike

这是我在此处提出的先前问题的后续问题:Exception: ObjectUnsubscribedError when working with Observables with RxJS and Angular2

在我的组件中,我等待数据从我编写的向 REST 服务发出 http 请求的服务到达。在我的组件 View 中,我引用了返回的数据......在我的组件中

import {Component} from 'angular2/core';
import {ROUTER_DIRECTIVES} from 'angular2/router';
import {UserContact, UserStatus} from '../../types/types';
import {UserDataService} from '../../services/user-data/UserDataService';

@Component({
selector: 'top-navigation',
directives: [...ROUTER_DIRECTIVES],
template: require('./top-navigation.html')
})

export class TopNavigation {

public currentUser: UserStatus;

constructor(public userDataService: UserDataService) {
// subscribe to the loginInUser observable to be notified when the current user is updated
this.userDataService.loginInUser.subscribe(
(currentUser) => {
this.currentUser = currentUser;
console.log(this.currentUser);
});
}

}

在我的 HTML 中,我有以下内容(在本例中为 top-navigation.html)我有以下代码,看看我如何将 currentUser 数据用作图像的 [src]:

<nav> 
<img [routerLink]="['Profile']" [src]="currentUser.profilePicture" class="img-circle nav-profile-img"
[ngClass]="{'gold-profile-pic': currentUser.goldUser, 'basic-profile-pic': !currentUser.goldUser}">
<a [routerLink]="['Profile']">Me</a>
<a [routerLink]="['Postbox']">Postbox</a>
<a [routerLink]="['Friends']">Friends</a>
<a [routerLink]="['Games']">Games</a>
<a [routerLink]="['Photos']">Photos</a>
</nav>

现在,由于 currentUser 的原始值为 null,因此 [src]="currentUser.profilePicture" 将是未定义的,我得到如下错误:

EXCEPTION: TypeError: Cannot read property 'profilePicture' of null in [currentUser.profilePicture in TopNavigation@9:40]
ORIGINAL EXCEPTION: TypeError: Cannot read property 'profilePicture' of null

我认为通过在 Angular1.* 中使用像 ng-src 这样的 [src] 可以防止此类错误并在 [src] 具有值后进行更新(在控制台日志中,有效的 http src 位于对象内)。我一定是做错了什么?

非常感谢您的提前建议。

最佳答案

你可以像这样在你的元素上添加一个 ngIf:

<nav *ngIf="currentUser">
<img [routerLink]="['Profile']" [src]="currentUser.profilePicture" class="img-circle nav-profile-img"
[ngClass]="{'gold-profile-pic': currentUser.goldUser, 'basic-profile-pic': !currentUser.goldUser}">
(...)
</nav>

在表达式中,如果对象的属性开箱即用为 null,则无法访问该对象的属性。您可以使用 ?(Elvis 运算符),如下所述:

<img [routerLink]="['Profile']" [src]="currentUser?.profilePicture" 

关于typescript - 在等待来自服务的异步/REST 数据时防止错误呈现到 View - RxJS/Angular2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35580852/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com