Franck Gomez
Franck Gomez

Reputation: 81

Use an Observable working with another Observable

I'm trying to show information, like that : user-settings.component.html

<div *ngIf="(_user | async) as user">
  <div fxLayoutAlign="center center">
    <h3>{{ user.surname + ' ' + user.name }}</h3>
  </div>
  <div>
    <span>
      <b>Email : </b>
      {{ user.email }}
    </span>
  </div>
[...]

Actually, in TS I do :

_user = this.db.collection('user').doc("IDENTIFICATION").valueChanges({ idField: 'id' }) as Observable<User>;

problem is that IDENTIFICATION is statics so I tried to do :

user-settings.component.ts

_user: Observable<User> = this.getUser();
[...]
getUser() {
  var userTempo: Observable<User>;

  this.authService.getUser().subscribe(user => {
    userTempo = this.db.collection('user').doc(user.uid).valueChanges({ idField: 'id' }) as Observable<User>;
    console.log(user.uid);
  });
  return userTempo;
}

to know this.authService.getUser() is comming from :

authService.ts

constructor(private afAuth: AngularFireAuth) {}
[...]
getUser() {
  return this.afAuth.user;
}

In this configuration, _user returns undefined, so nothing can be showed. Does anyone have an idea? Thank you for your time

Upvotes: 1

Views: 57

Answers (1)

VVS
VVS

Reputation: 293

You have to return an Observable, but what your returning is an object, as you’ve subscribed to it and assigned userTempo an object.


getUser(): Observable<User> {
  return this.authService.getUser().map(user => {
    console.log(user.uid);
    return this.db.collection('user').doc(user.uid).valueChanges({ idField: 'id' });
  });
}

If this.db.collection('user').doc(user.uid).valueChanges({ idField: 'id' }) returns an Observable then you will have to do this.

  getUser(): Observable<User> {
    return this.authService.getUser().switchMap(user => {
      return this.db.collection('user').doc(user.uid).valueChanges({ idField: 'id' });
    }).map(response => {
      return response;
    });
  }

Upvotes: 1

Related Questions