javascript - Typescript/Angular2 TypeError: Cannot read property of undefined -
ang2 component:
import { component, oninit } '@angular/core'; import { angularfire, firebaselistobservable, firebaseobjectobservable } 'angularfire2'; import chart 'chart.js' @component({ selector: 'app-prchart', templateurl: './app-prchart.component.html', styleurls: ['./app-prchart.component.css'] }) export class appprchartcomponent implements oninit { useremail: any; email: string; uid: any; records = []; newrecords = []; filteredrecords = []; labels = []; public barchartoptions:any = { scaleshowverticallines: false, responsive: true, legend: { display: false } }; public barchartcolors: [] =[ { backgroundcolor:'rgba(30, 136, 229, 1)' } ]; public barcharttype:string = 'bar'; constructor(public af: angularfire) { var auth = this.af.auth.subscribe( (user) => { if (user) { this.useremail = this.af.auth.subscribe(auth => { const queryobservable = af.database.list('/users/'+ auth.auth.uid +'/records/', { }); queryobservable.subscribe(querieditems => { this.records.push(querieditems); }); // filter records pr's this.newrecords = this.records[0].sort((a, b) => { if (a.movement === b.movement) { return a.weight >= b.weight ? -1 : 1 } return a.movement > b.movement ? 1 : -1 }) .filter((rec, i, arr) => { if (i === 0) return true return rec.movement !== arr[i - 1].movement }); let recordstring = json.stringify(this.newrecords); let recordparse = json.parse(recordstring); this.filteredrecords.push(recordparse); }); } else { } }); this.filteredrecords[0].foreach(function(snapshot) { this.labels.push(snapshot.movement); //barchartdata.push(snapshot.weight); }); //console.log(barchartlabels); //console.log(barchartdata); } ngoninit() { } }
i'm trying push items array keep getting following error:
typeerror: cannot read property 'labels' of undefined
the error occurs towards bottom line of code being run:
this.labels.push(snapshot.movement);
i've been playing hours , can't figure out i'm doing wrong, appreciated.
the issues this
changes inside callback functions. can fix using arrow functions capture correct this
:
this.filteredrecords[0].foreach((snapshot) => { this.labels.push(snapshot.movement); //barchartdata.push(snapshot.weight); });
or capturing this
in variable:
let = this; this.filteredrecords[0].foreach(function (snapshot) { that.labels.push(snapshot.movement); //barchartdata.push(snapshot.weight); });
this might useful: what 'this' in typescript
Comments
Post a Comment