How to return value inside subscribe Angular 4
You can't directly return totalQuestions like that, you need to use a subject to achieve that.
getTotalQuestions(idForm:string): Observable<string> {
let totalQuestions:number;
var subject = new Subject<string>();
this.getFirebaseData(idForm+"/Metadatos")
.subscribe(items => {
items.map(item => {
totalQuestions=item.Total;
console.log(totalQuestions);
subject.next(totalQuestions);
});
}
);
return subject.asObservable();
}
Usage: getTotalQuestion(idForm).subscribe((r)=>console.log(r))
Observable runs when you subscribe to it and what return from subscription is always a subscription object like setInterval. first sample: because this is a async call, second console.log won't wait for subscribe to finish before it executes.
getTotalQuestions(idForm: string) {
let totalQuestions: number;
return this.getFirebaseData(idForm + "/Metadatos").pipe(
map(items =>
items.map(item => {
totalQuestions = item.Total;
console.log(totalQuestions);
});
));
}
getTotalQuestions('231').subscribe(console.log)