How do I wait for the result of a query in the Firestore?

0

My problem is this:

I have a component that will list some categories, example:

categories: Observable<any[]>;

ngOnInit() {
    this.categories = this.categoryService.getAll();
}

In the service I need to query the user first (to get an attribute of it), only to query the categories. Example:

getAll() {
  this.userService.getCurrentUser().subscribe(user => {
    this.partnership_id = user.partnership_id;
    this.categories = this.db.colWithIds$<Category>('categories', ref => ref
      .where('partnership_id', '==', this.partnership_id)
      .where('enable', '==', true)
      .orderBy('name')
    );
  });
  return this.categories;
}

In this way, it returns the blank categories, because the return executes first the query in the firestore.

How to proceed in this case?

    
asked by anonymous 18.04.2018 / 04:19

1 answer

0

Firestore is a promise, that is, you need to pass a callback function on the getAll and at the end of the whole process, once you have the categories, then call the function with the result.

function petecas(categorias) {
    console.log(categorias);
}

getAll(petecas);

function getAll(petecas) {
      this.userService.getCurrentUser().subscribe(user => {
        this.partnership_id = user.partnership_id;
        this.categories = this.db.colWithIds$<Category>('categories', ref => ref
          .where('partnership_id', '==', this.partnership_id)
          .where('enable', '==', true)
          .orderBy('name')
        );
        petecas(this.categories);
      });
      /*return this.categories;*/
    }
    
18.04.2018 / 21:45