I cannot use the property data()
on DocumentSnapshot. It gives me an error in the console. here is the exact error:
auth.service.ts(72,20): error TS2339: Property 'data' does not exist on type 'Observable'.
I tried getting the data in multiple different ways. All of these techniques were errors.
Service:
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";
}
}
userD.get()
returns you an observable of DocumentSnapshot
, so you cannot call data()
on that. So you need to subscribe. In this case it seems that you want to return the data to a component (?) so I suggest you return an observable:
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");
}
}
Then in your component you subscribe to getUserName()
, either by manually calling subscribe
or using the async
pipe in template.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With