I'm a beginner with observables in Angular and I encountered an issue where I need to return a value from inside a subscribe method. This is my 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)
shows 4, but the second console.log(totalQuestions)
shows undefined.
I am aware that subscribe is asynchronous and that's why the second console.log(totalQuestions)
returns undefined. I can't figure out how to return the variable after the subscription has completed. 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)
doesn't show anything, while the second console.log(totalQuestions)
displays undefined. This is confusing me.
I hope someone can help clarify this concept for me. Thank you!