我不知道如何以我从firestore数据库中提取的角度访问我的.ts文件中的数据。我遇到的问题是我无法弄清楚如何访问.ts文件中的json数据。我发现了一个问题
Not able to access JSON data into angular(.ts) file
但答案并没有多大意义,当我试图实施它时,它对我没有用。
import { Component, OnInit } from '@angular/core';
import { AngularFireModule } from 'angularfire2';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { AngularFireAuth} from 'angularfire2/auth';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { moveIn, fallIn, moveInLeft } from '../router.animations';
interface User {
email: string;
name: string;
username: string;
uid: string;
}
@Component({
selector: 'app-members',
templateUrl: './members.component.html',
styleUrls: ['./members.component.css'],
animations: [moveIn(), fallIn(), moveInLeft()],
host: {'[@moveIn]': ''}
})
export class MembersComponent implements OnInit {
state: string = '';
name: any;
user_data: any;
userDoc: AngularFirestoreDocument<User>;
user: Observable<User>;
constructor(public af: AngularFireAuth,private router: Router, private afs: AngularFirestore) {
this.af.authState.subscribe(auth => {
if(auth) {
getAccountName();
this.userDoc = this.afs.doc("users_real/" + auth.uid);
this.user = this.userDoc.valueChanges();
console.log(this.user);
this.name = auth;
}
});
}
logout() {
this.af.auth.signOut();
console.log('logged out');
this.router.navigateByUrl('/login');
}
ngOnInit() {
}
}
下面的HTML
<div class="form-container" id="toolbar">
<header [@fallIn]="state">
<button (click)="logout()" class="basic-btn">Logout</button>
</header>
<div id="page" [@moveInLeft]="state">
<h2>Hey {{ user | async | json }}!</h2>
<img src="assets/images/filler.png" />
</div>
</div>
答案 0 :(得分:0)
一切都是可观察的。要正确创建user
和userDoc
属性,您必须使用RxJS运算符转换authState
Observable。
this.userDoc = this.af.authState.map(auth => auth ? this.afs.doc(`users_real/${auth.uid}`) : null);
所以现在你有了一个userDoc Observable,如果用户登录,它将指向Firestore中的一个位置;否则为空。
this.user = this.userDoc.switchMap(doc => doc ? doc.valueChanges() : of(null))
现在我们switchMap
用一个新的Observable替换了Observable,中止了之前的Firestore监听器;或者返回一个Observable为null。
您的视图现在可以按预期工作。