Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

407
Vistas
TypeScript/Angular2 TypeError: no se puede leer la propiedad de indefinido

Componente Ang2:

 import { Component, OnInit } from '@angular/core'; import { AngularFire, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2'; import Chart from '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: any [] =[ { 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 into 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() { } }

Estoy tratando de insertar elementos en una matriz, pero sigo recibiendo el siguiente error:

 TypeError: Cannot read property 'labels' of undefined

El error ocurre hacia la parte inferior donde se ejecuta esta línea de código:

 this.labels.push(snapshot.movement);

He estado jugando con esto durante horas y no puedo entender qué estoy haciendo mal, cualquier ayuda es apreciada.

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

El problema es que this cambia dentro de las funciones de devolución de llamada. Puede solucionar esto usando funciones de flecha que capturarán this correctamente:

 this.filteredRecords[0].forEach((snapshot) => { this.labels.push(snapshot.movement); //barChartData.push(snapshot.weight); });

O capturando this en otra variable:

 let that = this; this.filteredRecords[0].forEach(function (snapshot) { that.labels.push(snapshot.movement); //barChartData.push(snapshot.weight); });

Esto podría ser útil: ¿Qué es 'esto' en TypeScript?

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda