我已经在各种组件中使用firestore来使用snapshotChanges(
)和subscribe()
方法从集合和文档输出数据,但这几乎依赖于存在的数据,并且不会; t看看是否处理任何错误,例如,当找不到数据或检索到错误时。
我查看了文档,但是在获取数据时应该如何处理错误并不是很清楚。
如何捕获任何错误并将其记录到以下组件中的基于firestore的方法:?
import { Component, OnInit, AfterViewInit, ViewChild, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { MatPaginator, MatTableDataSource, MatSort } from '@angular/material';
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 { InvoiceItem } from '../invoiceItemModel';
@Component({
selector: 'app-view-invoice',
templateUrl: './view-invoice.component.html',
styleUrls: ['./view-invoice.component.scss']
})
export class ViewInvoiceComponent implements OnInit, AfterViewInit {
userId: string;
invoiceId: string;
invoice: Invoice;
itemsCollection: AngularFirestoreCollection<InvoiceItem>;
items: Observable<InvoiceItem[]>;
itemsData = new MatTableDataSource<InvoiceItem>();
tableColumns = [
'description',
'quantity',
'unitPrice',
'subtotal',
'taxCode',
'tax',
'total'
]
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
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 => {
this.invoice = snapshot.data() as Invoice;
})
this.itemsCollection = this.db.collection('/users').doc(this.userId).collection('/invoices').doc(this.invoiceId).collection('/items');
this.items = this.itemsCollection.snapshotChanges().map(changes => {
return changes.map(a => {
const data = a.payload.doc.data() as InvoiceItem;
data.id = a.payload.doc.id;
return data;
})
})
}
ngOnInit() {
}
ngAfterViewInit() {
this.getItems().subscribe(data => {
this.itemsData.data = data
})
this.itemsData.paginator = this.paginator;
this.itemsData.sort = this.sort;
}
getItems() {
return this.items
}
}