Search code examples
angulartypescriptangular4-forms

data loss when calling API in Angular 4


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.


Solution

  • 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