Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use the property data() from DocumentSnapshot

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";
  }
}
like image 754
user10601874 Avatar asked Nov 01 '19 02:11

user10601874


Video Answer


1 Answers

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.

like image 130
AT82 Avatar answered Sep 30 '22 17:09

AT82