'Issues with Angular/Firebase data
I'm sort of new to Angular and I'm working on a small project for an internship. I created the front-end and sending data into the database, but now I'm having issues with retrieving the data. I Googled some stuff and created an async function that's supposed to return the data, but when I do it's in a Zone Aware Promise format in the console, or when I use the .then() function, I can only console log the array of data, but cannot return it or pass it to a global variable. Here's the code from the component:
import {getDatabase, ref} from "firebase/database";
import {get} from "@angular/fire/database";
public async getVehicles() {
const db = getDatabase();
const snapshot = await get(ref(db, 'vehicles'));
return snapshot.val();
}
and when I do this:
this.getVehicles().then(data => {
console.log(data);
});
I get the array of data as I want it in the console. How can I get the data itself inside an outside variable, so I can use it and manipulate it as a regular array? Thanks in advance.
Solution 1:[1]
So I managed to solve this today with the help of my friend. Here's the code for anyone facing a similar issue, hope it helps.
public async getVehicles() {
const db = getDatabase();
// I made a loading component appear while the data is being fetched.
this.showLoading = true;
const snapshot = await get(ref(db, 'vehicles'));
// placed the promise value into a temporary object, for some reason the data is stored as an object where attributes are the list values I'm trying to get.
let temp = snapshot.val();
this.list = Object.keys(temp).map(index => {
return temp[index];
});
// took every element of the returned object and individually placed them into the main list
this.showLoading= false;
return snapshot.val();
}
Solution 2:[2]
- add a class field called list with
let list : any
- on anytime you want to get the data use:
this.getVehicles().then(data => {
this.list = data;
});
Or if you are on an async function you can use this:
this.list = await this.getVehicles();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rohith Balaji |
Solution 2 | jona303 |