Currently, I am tackling asynchronous issues by using promises. The strange thing is that when I run the promise for the first time, everything works perfectly. However, if I execute the same function twice, it throws a "Cannot read property of undefined" error. Reloading the page solves the problem, but it's not ideal for the user to refresh every single time.
I'm trying to understand why this happens. Is the previous promise still in progress? If so, how can I reset or refresh it?
I'm working with Typescript and Angular 4.
Below is the error message:
TypeError: Cannot read property 'ensenanza' of undefined
at SafeSubscriber._next (notas.service.ts:87)
(...and more lines of error information...)
And here is the section of code where I'm encountering the issue:
asignatura(key) { //obtain the rbd through cookies
var cod = [];
var total_listado = [];
var prom = Promise;
return prom.resolve(this.datoCurso(this.key)).then( dcurso => {
console.log(dcurso);
this.firebase.list('/sistema/asignaturaRBD').subscribe((asignaturaA) => {
for (let k = 0; k < asignaturaA.length; k++) {
const a = asignaturaA[k];
console.log(a.ensenanza +'=='+ dcurso[0].ensenanza +'&&'+ a.nivel +'=='+ dcurso[0].nivel+ '&&'+ a.rbd +'=='+ dcurso[0].rbd);
if (a.ensenanza == dcurso[0].ensenanza && a.nivel == dcurso[0].nivel && a.rbd == dcurso[0].rbd) {
cod.push({
asignatura: a.asignatura,
ensenanza: a.ensenanza,
nivel: a.nivel})
console.log("Passed through if");
}
}
});
return this.getNombreAsignatura(cod);
});
}
Code snippet of datoCurso function:
datoCurso(key) { //retrieve all data by key
let pushcurso = new Array();
this.firebase.list('/sistema/curso', {
query: {
equalTo: key,
orderByKey: key,
limitToFirst: 1
}
}).subscribe((datos) => {
for (let v = 0; v < datos.length; v++) {
const c = datos[v];
pushcurso.push({
ensenanza: c.cod_ensenanza,
nivel: c.nivel,
rbd: c.rbd
});
console.log(pushcurso[0].ensenanza+'--'+pushcurso[0].nivel+'--'+pushcurso[0].rbd);
}
});
return pushcurso;
}