开发者问题收集

Angular Firestore - 获取文档数据并分配给变量

2018-03-02
16083

我试图将从 firestore 文档收集的数据分配给在构造函数之前初始化的 Observable 类型的变量。

我通过将动态 invoiceId 字符串传递给 .doc() 搜索从集合中获取了数据,并且我可以将数据分配给局部变量(如下所示),但是当尝试将其分配给 this.invoice 时,出现以下错误:

Uncaught (in promise): TypeError: Cannot set property 'invoice' of undefined

-

组件:

import { Component, OnInit, 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 { Invoice } from '../invoiceModel';

@Component({
  selector: 'app-view-invoice',
  templateUrl: './view-invoice.component.html',
  styleUrls: ['./view-invoice.component.scss']
})

export class ViewInvoiceComponent implements OnInit {

  userId: string;

  invoiceId: any;

  invoicesCollection: AngularFirestoreCollection<Invoice>;
  invoices: Observable<Invoice[]>;

  invoice: Observable<Invoice>;

  constructor(private authService: AuthService, private db: AngularFirestore, private route: ActivatedRoute) {
      this.userId = this.authService.user.uid;

      this.route.params.subscribe(params => {
        this.invoiceId = params.id;
      })

      this.invoicesCollection = this.db.collection('/invoices');

      this.invoices = this.invoicesCollection.snapshotChanges().map(changes => {
          return changes.map(a => {
            const data = a.payload.doc.data() as Invoice;
            data.id = a.payload.doc.id;
            return data;
          })
      })
  }

  ngOnInit() {
    this.getInvoice();
  }

  getInvoice() {
    var docref = this.db.collection('/users').doc(this.authService.user.uid).collection('/invoices').doc(this.invoiceId);
    docref.ref.get()
        .then(function(doc) {
            if (doc.exists) {
                var invoice = doc.data(); <------WORKS
                // this.invoice = doc.data(); <------DOESN'T WORK
                console.log('Invoice data: ', doc.data());
            } else {
                console.error('No matching invoice found');
            }
    })
  }

}
3个回答

我也遇到了同样的问题。这让我抓狂了!!我是新手,但我似乎通过更改一行代码解决了您的问题:

.then(function(doc) {   //changed from
.then((doc) => {        //changed to (removed the function)

我甚至不明白这样做的后果,但范围现在正在分配变量的值。

HunterD
2018-05-08

如果您使用 AngularFire,您可以执行以下操作:

invoiceCol: AngularFirestoreCollection<Invoice>;
invoiceObservableArray: Observable<Invoice[]>;
invoiceArray: Invoice[];

constructor(private db: AngularFirestore) { } //--injection

getAllInvoice() { //getting data of DB
    this.invoiceCol= this.db.collection('yourInvoiceDbPath');
    return this.invoiceCol.valueChanges();
}

this.invoiceObservableArray.getAllInvoice();//calling method above

this.invoiceObservableArray.subscribe(invoice=> { //converting oberv in array
      this.invoiceArray = invoice;
    });

console.log(this.invoiceArray); //showing in console
Diego Venâncio
2018-05-21
getInvoice() {

let _this = this; <---***

    var docref = this.db.collection('/users').doc(this.authService.user.uid)
                     .collection('/invoices').doc(this.invoiceId);
    docref.ref.get()
        .then(function(doc) {
            if (doc.exists) {
                var invoice = doc.data(); <------WORKS
                // this.invoice = doc.data(); <------WORKS
                console.log('Invoice data: ', doc.data());
            } else {
                console.error('No matching invoice found');
            }
    })
  }
Sahan
2020-07-05