I'm new to observables in angular. I have a problem where I want to return a value inside a subscribe method. I have
the following method (getFirebaseData(idForm:string):observable <any[]>
):
getTotalQuestions(idForm:string){
let totalQuestions:number;
this.getFirebaseData(idForm+"/Metadatos")
.subscribe(items =>
{
items.map(item => {
totalQuestions=item.Total;
console.log(totalQuestions);
});
}
);
console.log(totalQuestions);
return totalQuestions;
}
the first console.log(totalQuestions)
prints 4 but the second console.log(totalQuestions)
prints undefined.
I understand that subscribe is an asynchronous operation and for that reason the second console.log(totalQuestions)
("In order to write the code") prints undefined, but I can not find the way to return the variable after the subscribe method has been completed. Now, if I change the subscribe to map:
getTotalQuestions(idForm:string){
let totalQuestions:number;
this.getFirebaseData(idForm+"/Metadatos")
.subscribe(items =>
{
items.map(item => {
totalQuestions=item.Total;
console.log(totalQuestions);
});
}
);
console.log(totalQuestions);
return totalQuestions;
}
the first console.log(totalQuestions)
does not print anything and the second console.log(totalQuestions)
prints undefined. It's something that I do not understand why it happens.
I hope you can help me clarify the concept that I do not understand. Thanks!