0

In my angular 4 application, I have two API calls in ngOnInit, I just trying to pass the data which returns from first API call to second.

But I received "Undefined" in API method.

Code:

ngOnInit() {

        this.http.get('https://api.ipify.org/?format=json').subscribe(
            data => {
                this.ip_Address=data['ip'],
                console.log(this.ip_Address),   
                error => console.error(error)
            });

            this.http.get(`http://localhost:xyz/api/data/INSERT_USER_SESSION/?IP_Address=${this.ip_Address}&Time=${this.date_and_time}&state=${this.session_Begin_Status}`)
            .subscribe(data => this.res = data['']);
}

Here I am passing the IP Address to the second API call but the value says "undefined". But I got the IP in the console.

Please tell me where I did the mistakes.

Ziauz
  • 773
  • 4
  • 22
Nikson
  • 900
  • 2
  • 21
  • 51

2 Answers2

1

The problem is that when you go outside of a subscribe method, the data which comes from the service will be undefined. You will see it in the console when it was not undefined, but after leaving the service its subscribe it will be put back to undefined. Consider using a switchmap or anything alike that. I also had this problem in this link. You can also do your second service in your first service.

BrianM
  • 951
  • 2
  • 12
  • 29
1

you can use the response of the data if the response is 200 and data body have data than parsing the data and call second service if first service has data in response so you don't get this error and another way is to make functions and call it in your onInIt

bhaumik shah
  • 206
  • 3
  • 15