06serseri
06serseri

Reputation: 63

Angular Firestore Map Document To Object

I am trying to get a single document from Firestore to an Anugular project and map it to an object to perform Update operations in HTML.

However when I subscribe to the document in ngOnInit() the get document method is called more than once.

The service is:

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

The component is: where "console.log(this.customer)" is called multiple times.

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

And then trying to work with this.customer variable in ts and html.

How can I map this document correctly to an object to work with in ts and html?

Thanks.

Edit: This question is also related to methods in ngOnInit() being called twice or multiple times Why is ngOnInit called twice?

Upvotes: 1

Views: 190

Answers (1)

06serseri
06serseri

Reputation: 63

It is fixed by unsubscribing on ngOnDestroy() from subscriptions on ngOnInit() in each component applicable as explained in the accepted answer Edit 3 Angular/RxJs When should I unsubscribe from `Subscription`

Thanks.

Upvotes: 1

Related Questions