导出 firebase 数据并将其设置为模板驱动形式的默认输入

Exporting firebase data and set it as default input in template driven form

我正在使用 angular 4.0.2、angularfire2 和 firebase 创建一个应用程序,当然。问题是我无法使用来自 angularfire2 的数据并将其设置为模型驱动或反应形式中使用的输入的默认输入值。 这是我的 add-invoice.component.ts

代码
ngOnInit(){
  const datafetch = firebase.database().ref().child('/invoices').orderByKey().limitToLast(1).once('value').then(snapshot => {
    const names = [];
    snapshot.forEach(function(childSnapshot) {
      var childKey = childSnapshot.key;
      var childData = childSnapshot.val();
      names.push(childSnapshot.val());
    });
    this.patchValues(names);
  });

  this.invoiceForm = this.fb.group({
    invoiceno: '',
    itemRows: this.fb.array([this.initItemRows()])
  });
}

patchValues(names){
  this.invoiceForm.patchValue({
    invoiceno: names.invoiceno
  });
  console.log(names);
}

数组显示在控制台中。

这是我的表格,即添加-invoice.component.html

<div class="form-group col-md-2">
<label>Invoice No.</label>
<input formControlName="invoiceno" class="form-control">

this.patchValues(names); 给你错误的原因

Cannot read property of patchValues 'undefined'

是因为您在代码中使用了 function,而不是 fat-arrow-syntax。使用 fat-arrow,您可以保留 this.

的上下文

所以代替这段代码(来自你未经编辑的post):

const datafetch = firebase.database().ref().child('/invoices').orderByKey().limitToLast(1).once('value').then(function(snapshot) {
  const names = [];
  snapshot.forEach(function(childSnapshot) {
    var childKey = childSnapshot.key;
    var childData = childSnapshot.val();
    names.push(childSnapshot.val());
  });
  name.push(names);
  console.log(name); // Here is the correct output I need below
});

你需要使用粗箭头语法,这样 this 就不会是 undefined:

  const datafetch = firebase.database().ref().child('/invoices').orderByKey().limitToLast(1).once('value').then(snapshot => {
    const names = [];
    snapshot.forEach(childSnapshot => {
      var childKey = childSnapshot.key;
      var childData = childSnapshot.val();
      names.push(childSnapshot.val());
    });
    this.patchValues(names);
  });