raj_tx
raj_tx

Reputation: 239

variable is defined in the Ionic

I have declared a variable in the constructor as below

constructor(public http: HttpClient) {
    this.data = null;
    this.http.get(this.url).subscribe((datas: any) => {
      this.dbUrl = datas[0].db_url2;
      console.log(this.dbUrl) // <- this output
    })
  }

Here I can see my output as

987456321

But I declare the variable in the same class in a different method.

getDetails() {
    let headers = new HttpHeaders();
    headers.append('Content-Type','application/json');
    console.log(this.dbUrl); // <- this output
    return this.http.get(this.dbUrl + 'details', { headers: headers})

  }

When I display the output It's displaying as Undefined. The dbUrl is a global variable. Can someone help me with this?

Upvotes: 1

Views: 92

Answers (1)

saperlipopette
saperlipopette

Reputation: 1693

In your first part of code, you're making a HTTP call, and this call subscribes to an Observable, it means that it does not return a result immediatly (since this is a web request). It observes the http.get changes.

In your second part of code, you're logging dbUrl, but the execution of your code is faster than the time needed by your app to complete the request. So here is why dbUrl is not set in the second log :

1) dbUrl is not defined
2) You're calling the http.get function, which is waiting from the server
3) You're calling getDetails, and you log dbUrl, which is null
4) You get a response from the server, and then you set dbUrl

Here is what you can do :

// Create a method to get the dbUrl. This functions will return a `promise`.
getUrl(){
    return new Promise<any>(
    function (resolve, reject) {
      this.http.get(this.url).subscribe((datas: any) => {
        this.dbUrl = datas[0].db_url2;
        resolve(this.dbUrl);
      }
}

And then, modify your getDetails method :

getDetails() {
    // If `this.dbUrl` has not been set yet
    if(this.dbUrl == undefined){
          this.getUrl()
          .then(url => {
            this.dbUrl = url;
            this.getDetails();
           })
          .catch(error => console.log(error))
        })
    }else{
        let headers = new HttpHeaders();
        headers.append('Content-Type','application/json');
        return this.http.get(this.dbUrl + 'details', { headers: headers})
    }
}

When you will call getDetails, if dbUrl is not ready yet, it will wait for its value and then recursively call getDails, and finally execute your request

Upvotes: 1

Related Questions