【发布时间】:2021-05-29 23:17:45
【问题描述】:
我在 Angular 中创建了一个客户服务,以从 Firebase 实时数据库中获取客户列表,如下所示:
getCustomers() {
return this.db.list('/customers', ref => ref.orderByChild('name')).snapshotChanges(); }
这会成功返回一个 JSON 数组。
然后我定义了Customer接口如下:
export interface Customer {
name: string;
address: string;
type: string;
phone: string;}
现在,在组件中,我正在尝试访问客户信息,如下所示:
customers: Customer[];
subscription: Subscription;
constructor(private customerService: CustomerService) {
this.subscription = this.customerService.getCustomers().subscribe(customers => this.customers = customers.map(c => c.payload.val()));
}
这给了我一个编译错误“Type Unknow is not assignable to type Customer[]”。 我的问题是:
- 将 payload().val() JSON 输出转换为客户类型的最佳方法是什么?
- 如何访问每条记录的密钥?(这是我的页面所必需的)。
非常感谢。
------ 根据 Le_Buzz 的建议和指导,更新了工作解决方案 ------
//首先我更新了客户界面以包含字段“key”,如下所示:
export interface Customer {
key: string;
name: string;
address: string;
type: string;
phone: string;}
//声明customers数组如下:
customers: Customer[] = [];
//然后订阅Observable如下:
subscription: Subscription;
this.subscription = this.customerService.getCustomers().subscribe(cus => {
cus.forEach(cus => {
const values = cus.payload.val();
const key = cus.payload.key;
this.customers.push({ name: values["name"], key: key, address: values["address"], type: values["type"], phone: values["phone"] })
})
})
【问题讨论】:
标签: json angular firebase-realtime-database angularfire