0

I'm working lately in a project where I use Angular and TypeScript. Doing the CRUD, I have the next code:

      // Return User's List from the DB
  get_AllUsers(){
    return this.fireservices.collection('users').snapshotChanges();
  }

  getAllUsersList() : User[]{
    let userList : User[];
    this.get_AllUsers().subscribe(users => {
      userList = users.map(e => {
          return {
            uid: e.payload.doc.id,
            ...
            visited: e.payload.doc.data()['visited']
          }
      }); //console.log(userList) here print the array correctly
    });
  return userList; //Here I received an undefined array, but I want the array with the data
  }

I'm using Firebase as a DB. I have a model created for User (one type of data saved in DB) and I want that the return, returns array of Users listed, but I receive an undefined array. How could I solve that? I've put some annotations to explain the error.

PD. Is there any way to receive Firebase data directly in a model created to use it in the application ('User' in this case)?

Thanks.

2 Answers2

2

This is an asynchronous call, it should be handled the same way.

Here you're returning an undefined variable, and you're not returning the response of the request. Instead return an observable and subscribe to the calling method. For ex: _.getAllUsersList().subscribe(x => ...)

getAllUsersList() : Observable {
    return this.get_AllUsers().pipe(map(e => {
          return {
            ... // your code
          })
      });
    });
  }
Sam
  • 572
  • 3
  • 11
  • function map used throw me error. Error is next: Property 'map' does not exist on type 'Observable[]>. PD. I have added Observable in the return value – Ángel Baeza Nov 02 '20 at 17:32
1

Try to do it directly:

function getAllUsersList() : User[] {
  let userList : User[] = [];
  this.get_AllUsers().subscribe(users => {
    users.map(e => {
      userList.push({
        uid: e.payload.doc.id,
        visited: e.payload.doc.data()['visited']
      });
    });
  });
  return userList;
}
ricardo-dlc
  • 466
  • 1
  • 3
  • 9
  • If I do this, all the function throw error due to the first return. Error is next: Type 'Subscription' is missing the following properties from type 'User[]': length, pop, push, concat, and 26 more – Ángel Baeza Nov 02 '20 at 17:25
  • If the `return` gives you what you want, you can assert the type adding `as User[]` next to the `return`. – ricardo-dlc Nov 02 '20 at 18:49
  • Do that gives me the same error. You can see in: https://i.imgur.com/YfpnvDd.png – Ángel Baeza Nov 02 '20 at 22:26
  • It suggests to convert to `unknown` first before convert to `User[]`. Have you tried that? – ricardo-dlc Nov 03 '20 at 03:01
  • 1
    Check my update, if this doesn't work you can [check this](https://stackoverflow.com/questions/47732157/using-observable-and-subscribe-in-angular-with-firebase) in order on how to implement an Observable like the other answer sugests – ricardo-dlc Nov 03 '20 at 14:04