-2

Sorry for that bad title. I am getting data from api with httpclient and when I console.log that data inside of a subscribe everything works fine, but when I do: this.launches = data and then try to console.log that what I see is "Undefined" in the console

console o/p

    launches:LaunchRootObject;

    showLaunches(){
    this.client.GetAllLauches().subscribe((data:LaunchRootObject) =>{
      console.log(data); //this is working
      this.launches = data;
    });
    }

    ngOnInit(): void {
    this.showLaunches();
    console.log(this.launches)  //this shows "Undefined"
  }

This is a part of a http service:

    GetAllLauches(){
    return this.http.get<LaunchRootObject>(this.base_url + 'launch');
  }
Dewanshu
  • 532
  • 2
  • 16
  • The problem is the first variable works great but something happens when calling the second console.log, the second one shows undefined – Arek123113 Jun 30 '20 at 15:04
  • 1
    Does this answer your question? [How do I return the response from an Observable/http/async call in angular?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular) – R. Richards Jun 30 '20 at 15:14

2 Answers2

0

Its async, ngOnInit is executed before showLaunches(). What happens is:

  1. ngOnInit() is called by angular
  2. this.showLaunches() is called by ngOnInit
  3. this.client.GetAllLauches() is called (not completed)
  4. console.log(this.launches) is called but the http as not been completed yet which is why you see undefined
  5. this.client.GetAllLauches() completes and get in your subscribe
  6. console.log(data); works
  7. this.launches is now being assigned but its too late

You could use something like this if you want to print the data from the onInit when its available:

    const subscription: new Subscription();
            
    ngOnInit(): void { 
        this.subscription.add(this.client.GetAllLauches()
            .subscribe((data:LaunchRootObject) => { 
                console.log(data); //this is working
                    this.launches = data;
                })
            })
    }
           


      
ukn
  • 1,723
  • 1
  • 14
  • 24
0

Subscriptions are used to handle async method call. Thus, the code inside the subscribe() method is executed only when the async method return its result (in your case http call).

While waiting for the async response, the program continues and execute the console.log(this.launches).

That's why your console.log(this.launches) is executed before your console.log(data) and before subscribe method callback this.launches is undefined.