Reputation: 27
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
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
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