Angular/Firebase 数据的问题

Issues with Angular/Firebase data

我是 Angular 的新手,我正在做一个小项目实习。我创建了前端并将数据发送到数据库中,但现在我在检索数据时遇到了问题。 我在谷歌上搜索了一些东西并创建了一个应该 return 数据的异步函数,但是当我在控制台中以 Zone Aware Promise 格式执行它时,或者当我使用 .then() 函数时,我只能控制台记录数据数组,但不能 return 它或将其传递给全局变量。这是组件的代码:

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

当我这样做时:

this.getVehicles().then(data => {
  console.log(data);
});

我在控制台中得到了我想要的数据数组。我如何才能将数据本身放入外部变量中,以便我可以使用它并将其作为常规数组进行操作? 提前致谢。

  1. 添加一个名为列表的 class 字段 let list : any
  2. on anytime you want to get the data use:
this.getVehicles().then(data => {
    this.list = data;
});

或者如果你使用的是异步函数,你可以使用这个:

this.list = await this.getVehicles();

所以我今天在我朋友的帮助下设法解决了这个问题。这是任何遇到类似问题的人的代码,希望它有所帮助。

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