How to return a Promise from an Angularfireobject using @angular/fire in Angular(V6+)

Asked

Viewed 66 times

5

Hello, I’m working on a project in Angular where I need to return a Promisein a particular service. My code is like this:

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';

@Injectable({ providedIn: 'root' })
export class UserService {

  readonly baseUrl: string = 'user';

  constructor(
    private afDb: AngularFireDatabase
  ) { }

  object(id: string) {

    return this.afDb
      .object(`${this.baseUrl}/{${id}}`)
      .snapshotChanges()
      .toPromise()
  }

}

The problem is I can’t capture the Promise when using the function userService.object inside the components. I’m doing this:

@Component({ selector: 'login', templateUrl: './login.html' })
export class Login {

  uid: 'teste'; 

  constructor(
    public userService: UserService
  ) { }

  login() {
    this.userService.object(this.uid)
      .then(res => console.log(res))
      .catch(err => console.error(err));
  }

}

What I need to do that my service can return a promise with the object that comes from AngularFireDatabase?

1 answer

1


Try to use async await in your service

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';

@Injectable({ providedIn: 'root' })
export class UserService {

  readonly baseUrl: string = 'user';

  constructor(
    private afDb: AngularFireDatabase
  ) { }

  async object(id: string) {

    return await this.afDb
      .object(`${this.baseUrl}/{${id}}`)
      .snapshotChanges()
      .toPromise()
  }

}

Browser other questions tagged

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