Exporting firebase data and set it as default inpu

2019-08-03 16:04发布

I am creating an app using angular 4.0.2, angularfire2, and firebase, off course. What the problem is I am not able to use the data from angularfire2 and set it as default input value of an input used in model-driven or reactive form. Here is my code for 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);
}

Array being Shown up in console.
Console Image

Here is my form i.e. add-invoice.component.html

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

1条回答
Root(大扎)
2楼-- · 2019-08-03 16:58

The reason for that this.patchValues(names); gave you error

Cannot read property of patchValues 'undefined'

was because you are using function in your code, instead of fat-arrow-syntax. With fat-arrow you keep the context of this.

So instead of this piece of code (from your unedited 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
});

You need to use fat-arrow syntax and then this will not be 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);
  });
查看更多
登录 后发表回答