[Solved] How do I return the response from an Observable/http/async call in angular?

Article Mohaimen Khalid

Problem:

I have service which returns an observable which does an http request to my server and gets the data. I want to use this data but I always end up getting undefined. What's the problem?

   //Service 
    @Injectable() 
    export class EventService {

    constructor(private http: Http) { }  

    getEventList(): Observable<any>{    
      let headers = new Headers({ 'Content-Type': 'application/json' });
      let options = new RequestOptions({ headers: headers });

      return this.http.get("http://localhost:9999/events/get", options)
            .map((res)=> res.json())
                    .catch((err)=> err)
      }
    }      
   //Component
    @Component({...})
    export class EventComponent
    {
        myEvents: any;
        constructor(
            private es: EventService 
         ) { }
         ngOnInit(){
            this.es.getEventList() 
               .subscribe((response) =& gt;{
                   this.myEvents = response;
                });
            console.log(this.myEvents); //This prints undefined!
    }}
Discuss about the problem and possible solutions:


Reason:

The result showing undefined, showing that result cause if you are making an asynchronous operation.

Meaning of this, In the component you’ve called a function getEventList() . It takes some times to complete the process. It also depends on your internet speed. Here looks your http request call –

this.es.getEventList()

this line will be executed immediately. And the value shows undefined before the response.

This problem seems like -

   ngOnInit(){
       setTimeout(()=>{
           this.myEvents = response;
       }, 5000);
    
       console.log(this.myEvents); //This prints undefined!
   }

Solution:

So how to solve this problem...


We will use a callback function which is the subscribe method. Because when the data comes from the server it'll be inside the subscribe.

So now change your code to –

   this.es.getEventList()    
    .subscribe((response)=>{
        this.myEvents = response;
        console.log(this.myEvents); //<-- not undefined anymore
   });

Alternatively, you can use a promise, when promise data comes from then function call and call subscribe code into then function.


Note: Don’t try to convert async to sync operation. Suppose that one of your async operations takes 3 minutes to complete a request, if we didn't have the async operations the interface would freeze for 3 minutes.