In my component, I have loaded a firestore document and converted it into a plain js object within the constructor. However, when trying to access the field values in the template, there is a slight delay in loading them. This results in an error being displayed in the browser console stating "Cannot read property 'id' of undefined" when trying to access {{invoice.id}}.
My understanding is that anything defined in the constructor should be immediately available in the view upon initialization. So, why is this error happening and how can I prevent it?
view-invoice.component.html:
<h4 class="page-title">Invoice Summary</h4>
<p>ID: {{ invoice.invoiceId }}</p>
<p>Reference: {{ invoice.reference }}</p>
<p>Date: {{ invoice.date | date: 'dd/MM/yyyy' }}</p>
view-invoice.component.ts:
import { Component, OnInit, AfterViewInit, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { AngularFireDatabase } from 'angularfire2/database';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { AuthService } from '../../services/auth.service';
import { InvoiceService } from '../invoice.service';
import { Invoice } from '../invoiceModel';
import 'rxjs/add/operator/mergeMap';
@Component({
selector: 'app-view-invoice',
templateUrl: './view-invoice.component.html',
styleUrls: ['./view-invoice.component.scss']
})
export class ViewInvoiceComponent implements OnInit, AfterViewInit {
userId: string;
invoiceId: any;
// invoice: Observable<Invoice>;
invoice: any;
constructor(private authService: AuthService, private invoiceService: InvoiceService, private db: AngularFirestore, private route: ActivatedRoute) {
this.userId = this.authService.user.uid;
this.route.params.subscribe(params => {
this.invoiceId = params.id;
})
this.db.collection('/users').doc(this.userId).collection('/invoices')
.doc(this.invoiceId).ref.get().then(snapshot => {
const data = snapshot.data();
this.invoice = data;
})
}
ngOnInit() {
this.getInvoice();
}
ngAfterViewInit() {
}
}