How to wait for the result of a Firestore query?

Asked

Viewed 214 times

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 make a query first on the user (to get an attribute from it), and only then consult 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;
}

Only this way, returns the empty categories, because Return runs before the query in the firestore.

How to proceed in that case?

  • The value is only available within the same subscribe pq and assincriono. you can place a loading until the query returns or use async pipe.

1 answer

0


Firestore is a file, that is, you need to pass a callback function in "getAll" and at the end of the whole process, already when you are with the categories then call the function passed 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;*/
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.