Typescript 在等待来自服务的异步/REST数据时防止错误呈现以查看-RxJS/Angular2
这是我在这里提出的前一个问题的后续问题: 在我的组件中,我等待数据从我编写的向REST服务发出http请求的服务到达。在我的组件视图中,我引用了返回的数据,因此。。。在我的组件中Typescript 在等待来自服务的异步/REST数据时防止错误呈现以查看-RxJS/Angular2,typescript,angular,rxjs,Typescript,Angular,Rxjs,这是我在这里提出的前一个问题的后续问题: 在我的组件中,我等待数据从我编写的向REST服务发出http请求的服务到达。在我的组件视图中,我引用了返回的数据,因此。。。在我的组件中 import {Component} from 'angular2/core'; import {ROUTER_DIRECTIVES} from 'angular2/router'; import {UserContact, UserStatus} from '../../types/types'; import {U
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>
我认为,在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>
我认为这可能是答案,但我以前不需要使用它。这是我第一次听说“Elvis操作符”。@MikeSav,模板开发指南中提到了Elvis操作符:
<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>
<img [routerLink]="['Profile']" [src]="currentUser?.profilePicture"