Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return value inside subscribe Angular 4

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!

like image 322
AlejoDev Avatar asked Apr 02 '18 03:04

AlejoDev


People also ask

Can you return a subscription Angular?

To return data from subscribe with Angular, we can return the map observable. to call http. get to make a get request to the path . Then we call map with a callback that returns the response JSON with res.

What does subscribe method return in Angular?

The subscribe() call returns a Subscription object that has an unsubscribe() method, which you call to stop receiving notifications.

How do we get the value back from an observable in our component?

Observable values can be retrieved from any locations. The source sequence is first pushed onto a special observer that is able to emit elsewhere. This is achieved with the Subject class from the Reactive Extensions (RxJS). Store value onto the observer.


2 Answers

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))

like image 103
Rajani Kanth Avatar answered Oct 02 '22 12:10

Rajani Kanth


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) 
like image 41
Fan Cheung Avatar answered Oct 02 '22 12:10

Fan Cheung