【发布时间】:2021-05-01 01:59:53
【问题描述】:
这是我用于访问 firebase 数据的函数。
export class SubscriptionProductComponent implements OnInit {
private products: any;
private customer: any;
constructor(private database: AngularFireDatabase,private route: Router) {
this.customer = this.database.database.ref().child('/Products/');
this.customer.orderByChild("productType").equalTo("subscription").on('value', function (snapshot) {
console.log(snapshot.toJSON());
this.products = snapshot.toJSON();
console.log(this.products);
});
}
ngOnInit() {}
//Some other function are here
}
我收到的错误是
core.js:6210 ERROR TypeError: Cannot set property 'products' of undefined
at subscription-product.component.ts:34
at valueCallback (index.esm.js:14463)
at CallbackContext.push.6Uf2.CallbackContext.onValue (index.esm.js:12274)
at index.esm.js:13118
at exceptionGuard (index.esm.js:638)
at eventListRaise (index.esm.js:11082)
at eventQueueRaiseQueuedEventsMatchingPredicate (index.esm.js:11057)
at eventQueueRaiseEventsForChangedPath (index.esm.js:11044)
at repoOnDataUpdate (index.esm.js:11261)
at PersistentConnection.repo.server_ [as onDataUpdate_] (index.esm.js:11163)
请帮我解决这个问题。
【问题讨论】:
-
你在哪里定义
this.products?似乎没有名为products的变量。 -
像往常一样,它位于类声明之后的代码开头。
-
console.log(snapshot.toJSON());是否产生任何输出? -
是的,@Lynx242 console.log(snapshot.toJSON());根据需要返回准确的输出。但问题是如何全局访问它?
-
回调 (this.products) 中的“this”不是您所期望的。将回调中的函数更改为箭头,您应该没问题。功能(快照)应该是(快照)=>
标签: angular firebase-realtime-database