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

nic*_*ook 6 firebase typescript angular google-cloud-firestore

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

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

未捕获(承诺):类型错误:无法设置未定义的属性“发票”

——

成分:

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

}
Run Code Online (Sandbox Code Playgroud)

小智 1

我也在和同样的事情作斗争。这让我发疯了!我是新手,但我似乎通过更改一行代码解决了您的问题:

.then(function(doc) {   //changed from
.then((doc) => {        //changed to (removed the function)
Run Code Online (Sandbox Code Playgroud)

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

  • 这是因为箭头函数与“函数”的作用域不同。后者基本上为“this”定义了一个新的范围。 (4认同)