0

I want to push the values into a array like below when i retrieve values from firebase database

 columns: any[];
 this.columns = [
{ columnDef: 'FirstName', header: 'First Name',    cell: (element: any) => `${element.FirstName}` },
{ columnDef: 'LastName', header: 'Last Name',    cell: (element: any) => `${element.LastName}` },
];

Here is what i tried so far.........

 this.af.list('/datalist', {
 query: {
    limitToLast: 200,
    orderByChild: 'name',
    equalTo: 'spiderman',
    preserveSnapshot: true
  }
 }).subscribe(snapshot=>{
   if(snapshot!=undefined){
    snapshot.forEach(function(childSnapshot) {

    this.columns.push( { columnDef: childSnapshot.heroname, header: childSnapshot.herotitle,    cell: (element: any) => `${element.heroname}` });
    this.displayedColumns = this.columns.map(c => c.columnDef);

    return false;
    });
   }
  });

Error with above code is Cannot read property 'columns' of undefined

Even though i declared the columns array globally its not recognizing it.

In HTML i want to use like this....

   <ng-container *ngFor="let column of columns" [cdkColumnDef]="column.columnDef">
    <mat-header-cell *cdkHeaderCellDef>{{ column.header }}</mat-header-cell>
    <mat-cell *cdkCellDef="let row">{{ column.cell(row) }}</mat-cell>
   </ng-container>

Any hint is appreciated. Thank you.

DEV
  • 949
  • 1
  • 9
  • 29
  • It is not recognising the `this` keyword. You may assign it to a variable prior to the function call `self = this` and then use variable `self` inside your subscription. – GCSDC Mar 17 '19 at 23:39

1 Answers1

0

You are getting this error because of the following code:

snapshot.forEach(function(childSnapshot) {

this.columns.push( { columnDef: childSnapshot.heroname, header:  childSnapshot.herotitle,    cell: (element: any) => `${element.heroname}` });
this.displayedColumns = this.columns.map(c => c.columnDef);

return false;
});

Here forEach takes a callback function as it's first parameter, and this inside the callback is in a different context and therefore you get that error.

To solve this, you need to use arrow function:

An arrow function does not have its own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope they end up finding this from its enclosing scope.

Basically what it means that this inside the arrow function will refer to this in which the arrow function was defined, so you will be able to do the following:

snaphot.forEach((childSnapshot)=>{

this.columns.push( { columnDef: childSnapshot.heroname, header: childSnapshot.herotitle,    cell: (element: any) => `${element.heroname}` })
this.displayedColumns = this.columns.map(c => c.columnDef);

return false;
});
Peter Haddad
  • 78,874
  • 25
  • 140
  • 134