0

I am trying to pull data from firebase just once. With this code it subscribes and watches for changes and updates value realtime.

this.profileData = this.fire.authState.switchMap(auth => this.db.object(`profile/${auth.uid}`).snapshotChanges().map(action => {
      const $key = action.payload.key;
      const data = { $key, ...action.payload.val() };
      return data;

    })).subscribe(profile => {

      this.profileData = profile;


      console.log(this.profileData.username); // this is working.

    });

I was trying something like this but its not working

this.profileData = this.fire.authState.switchMap(auth => this.db.object(`profile/${auth.uid}`)).take(1).subscribe(profile =>{

console.log(profile.username);

}));
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • The `take(1)` should be working, see: [Just get the value once with no subscription](https://github.com/angular/angularfire2/issues/456#issuecomment-241509299). – Grimthorr Oct 23 '17 at 11:17
  • this.profileData = this.fire.authState.switchMap(auth => this.db.object(`profile/${auth.uid}`)).take(1); console.log(this.profileData.username); this returns undefined ? – Yunus Emre Guney Student Oct 23 '17 at 12:01
  • with console.log(this.profileData) i got this : http://prntscr.com/h0waiy – Yunus Emre Guney Student Oct 23 '17 at 12:13
  • `profileData` is an Observable as we can see from your image, you need to subscribe to it, to be able to console log it – AT82 Oct 23 '17 at 13:27

2 Answers2

0

When you are using your own observables you have to care about unsubscribe.

Angular components have a lot of lifecycle hooks like ngOnInit, ngOnChange etc. You have also function ngOnDestroy and good practise is to unsubscribe your observables in that hook.

I think if you want to fetch data only once the best option is to call function where you unsubscribe. Here you have link with more info about: Angular/RxJs When should I unsubscribe from `Subscription`

Adam A
  • 157
  • 1
  • 18
0

Possible solution is get the subscription and unsubscribe once you received a value

let subs$ = this.fire.authState.switchMap(auth => 
 this.db.object(`profile/${auth.uid}`).snapshotChanges().map(action => {
  const $key = action.payload.key;
  const data = { $key, ...action.payload.val() };
  return data;

})).subscribe(profile => {

  this.profileData = profile;
  subs$.unsubscribe()



  console.log(this.profileData.username); // this is working.

});
Auqib Rather
  • 396
  • 1
  • 10