Ángel Baeza
Ángel Baeza

Reputation: 27

Undefined after use and save values into an array in map function (Angular, TypeScript)

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.

Upvotes: 0

Views: 313

Answers (2)

ricardo-dlc
ricardo-dlc

Reputation: 486

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;
}

Upvotes: 1

Sam
Sam

Reputation: 632

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
          })
      });
    });
  }

Upvotes: 2

Related Questions