Ad

Service Slower Than Page | Ionic 4 | Firebase

First of all: I am very new to coding in general. Sorry if this question is stupid ^^ I tried to build a simple app in ionic with firestore. Now i wanted to create some simple services. Now i got the problem, that the service is getting the data after the "this.userData = this.userService.currUser" was passed. That meas, i have no data in this.userData.

How to do this correctly? :/

Thanks!

The service:

export class UserServiceService {
  public currUser: any;
  private currUserRef: any;

  constructor(private afs: AngularFirestore, public afAuth: AngularFireAuth) {
    const currUserId = afAuth.auth.currentUser.uid;
    this.currUserRef = afs.collection('users').doc(currUserId).valueChanges();
    this.currUser = this.currUserRef.subscribe(data => {
      return data;
    });
  }
}

The page:

export class EventlistPage implements OnInit {

  private events: Observable<Event[]>;
  private userData;

  constructor(private eventService: EventService, private afAuth: 
  AngularFireAuth, public userService: UserServiceService) { }

  ngOnInit() {
    this.events = this.eventService.getEvents();
    this.userData = this.userService.currUser;
  }

}
Ad

Answer

Convert your Observable to Promise and use .then()

So your service will look like this

export class UserServiceService {
  public currUser: any;
  private currUserRef: any;
  constructor(private afs: AngularFirestore, public afAuth: AngularFireAuth) {
    const currUserId = afAuth.auth.currentUser.uid;
    this.currUserRef = afs.collection('users').doc(currUserId).valueChanges();
  }
  getDataFromFireStore(){
   return this.currUserRef.toPromise();
  }
}

And in your user class

export class EventlistPage implements OnInit {
  private events: Observable<Event[]>;
  private userData;
  constructor(private eventService: EventService, private afAuth: 
  AngularFireAuth, public userService: UserServiceService) { }

  ngOnInit() {
    this.events = this.eventService.getEvents();
    this.userService.getDataFromFireStore().then(data => this.userData = data);
  }

}
Ad
source: stackoverflow.com
Ad