Angular 可观察基础知识

Angular observables basics

我有一个来自 firebase 的观察结果。

我服务中的相关代码是这样的:

interface User {
uid: string;
email: string;
}    

public user: Observable<User>;

getUserDetails(uid) {
this.userDocument = this.afs.collection('users').doc(uid)
this.user = this.userDocument.valueChanges();
return this.user
}

ngOninit() {
this.user = this.getUserDetail(uid)
}

要查看可观察对象中的变量,我有以下代码:

<h1>Json: {{user | async | json}}</h1>

这又吐出:

Json: {"email": "xxx@somemail.com", "uid": "DbeFlYvdbqTP12vPE7x4hJFashe2" }

然而,以下内容让我一无所获。为什么这不起作用?

<h1>Email: {{user.email | async}} </h1>
<h1>Uid: {{user.uid | async}} </h1>

应该这样做,

 <h1>Email: {{(user| async)?.email}} </h1>
 <h1>Uid: {{(user | async).uid}} </h1>

您还可以使用 ngIf 来避免多个异步管道:

<div *ngIf="user|async as userObj">{{userObj|json}} is just an object now</div>