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

时间:2016-02-23 14:59:50

标签: typescript angular rxjs

这是我在此问过的上一个问题的后续问题:Exception: ObjectUnsubscribedError when working with Observables with RxJS and Angular2

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

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中使用[src]就像ng-src一样。*会阻止这样的错误并在[src]有一个值时更新(在控制台日志中有效的http src在对象内)。我一定做错了什么?

非常感谢您提前获得的建议。

1 个答案:

答案 0 :(得分:2)

您可以在元素上添加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>

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

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