Angular Firestore将文档映射到对象



我正试图将一个文档从Firestore获取到一个Anugular项目,并将其映射到一个对象,以在HTML中执行更新操作。

但是,当我在ngOnInit((中订阅文档时,get-document方法会被多次调用。

服务是:

async getUid() {
return (await this.angularFireAuth.currentUser).uid;
}
getCustomer(id: string, userId: string) {
this.customerDocument = this.angularFireStore
.collection('customers')
.doc(userId)
.collection('customersByUid')
.doc(id);
return this.customerDocument.snapshotChanges();
}

组成部分是:其中";console.log(this.customer(";被调用多次。

ngOnInit() {
this.createCustomerForm();
const docId = this.customerService.customerData.id;
console.log('DOCID IS: ' + docId);
this.customerService.getUid().then((x) => {
this.userId = x;
console.log('USER ID IS: ' + x);
this.customerService
.getCustomer(docId, this.userId)
.subscribe((action) => {
(this.customer = {
id: action.payload.id,
...(action.payload.data() as ICustomer),
}),
(err: any) => {
console.debug(err);
};
console.log(this.customer);
});
});
}

然后尝试在ts和html中使用这个.customer变量。

如何将此文档正确映射到要在ts和html中使用的对象?

谢谢。

编辑:这个问题也与ngOnInit((中的方法被调用两次或多次有关。为什么ngOnInit被调用了两次?

它是通过在ngOnDestroy((上从每个适用组件的ngOnInit((上的订阅中取消订阅来修复的,如接受的答案编辑3 Angular/RxJs我应该何时取消订阅`Subscription`

谢谢。

最新更新