我无法使用DocumentSnapshot上的属性data()
。它在控制台中给我一个错误。这是确切的错误:
auth.service.ts(72,20):错误TS2339:类型“可观察”的属性“数据”不存在。
我尝试以多种不同方式获取数据。所有这些技术都是错误。
服务:
constructor(
private afAuth: AngularFireAuth,
private afs: AngularFirestore,
private router: Router,
public db: AngularFirestore
) {
this.user = afAuth.authState;
this.user.subscribe((user) => {
if (user) {
this.userDetails = user;
console.log(this.userDetails);
} else {
this.userDetails = null;
}
})
}
getUserName() {
(this.isLoggedIn()){
const userD = this.db.collection('users').doc(this.userDetails.uid);
const doc = userD.get();
return doc.data().firstName;
} else {
console.log('user not logged in');
return "nothing";
}
}
答案 0 :(得分:1)
userD.get()
为您返回DocumentSnapshot
的观测值,因此您不能在其上调用data()
。因此,您需要订阅。在这种情况下,您似乎想将数据返回到组件(?),所以我建议您返回一个可观察的对象:
import { take, map } from 'rxjs/operators';
// ...
getUserName() {
if(this.isLoggedIn()){
const userD = this.db.collection('users').doc(this.userDetails.uid);
const doc = userD.get();
return doc.pipe(
// add take if you only want data one time, which closes subscription
take(1),
map(d => d.data().firstName)
)
} else {
console.log('user not logged in');
// need to return an observable
return of("nothing");
}
}
然后在组件中通过手动调用getUserName()
或使用模板中的subscribe
管道来订阅async
。
答案 1 :(得分:0)
根据本文档,您不能使用userD.get().data()
。尝试userD.get()
或userD.data()
const userD = this.db.collection('users').doc(this.userDetails.uid);
var getOptions = {
source: 'cache'
};
userD.get(getOptions).then(function (doc) {
// check if firstname exist in doc
console.log(doc)
}).catch(function (error) {
});
我跟随https://cloud.google.com/firestore/docs/query-data/get-data。