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 Answers 2

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
          })
      });
    });
  }
Sign up to request clarification or add additional context in comments.

1 Comment

function map used throw me error. Error is next: Property 'map' does not exist on type 'Observable<DocumentChangeAction<unknown>[]>. PD. I have added Observable<User[]> in the return value
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;
}

5 Comments

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
If the return gives you what you want, you can assert the type adding as User[] next to the return.
Do that gives me the same error. You can see in: i.imgur.com/YfpnvDd.png
It suggests to convert to unknown first before convert to User[]. Have you tried that?
Check my update, if this doesn't work you can check this in order on how to implement an Observable like the other answer sugests

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.