The Ionic framework has a defined variable

In my code, I have initialized a variable inside the constructor like this:

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) // <- output here
    })
  }

The output that I see is:

987456321

Later, in a different method within the same class, I reference the variable again:

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

  }

However, when I try to display the output, it shows as Undefined. The dbUrl is declared as a global variable. Can anyone assist me with solving this issue?

Answer №1

The initial part of your code involves making an HTTP call, which subscribes to an Observable. This means that the result is not returned immediately (due to it being a web request) and instead observes changes in the http.get method.

In the subsequent part of the code, you're logging the value of dbUrl. However, the code executes faster than the time required for the app to complete the request. As a result, dbUrl is not defined in the second log due to:

1) dbUrl is not yet defined
2) The http.get function is waiting for a response from the server
3) You call getDetails and log dbUrl, which is currently null
4) After receiving a response from the server, dbUrl is then set

To address this issue, consider following these steps:

// Define a method to retrieve the dbUrl asynchronously using 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);
      }
}

Next, update your getDetails method as follows:

getDetails() {
    // Check if dbUrl has been initialized
    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 calling getDetails, if dbUlr is not yet available, it will wait for its initialization before recursively calling getDails and executing the request.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Material-UI: Unforeseen TypeError arises while toggling between two Drawer elements

Note: I am utilizing material-ui 3.3.0 My goal is to have two <Drawer> components displayed on a page, with one sliding in from the left and the other from the right. In an <AppBar>, there are two <Button> components that toggle the visi ...

Capture data from a Telegram bot and store it in a Google Sheet

I am trying to use a spreadsheet through a Telegram bot as a TODO list so that when I input something on my phone, it is saved in the spreadsheet. (I'm following this tutorial https://www.youtube.com/watch?v=XoTpdxbkGGk, which seems accurate with Goog ...

Unsure about the commit hash referenced in the tsd.json file

Explore the history of angular-ui-router d.ts file using the commit hash Within my tsd.json file, I have the following details: { "version": "v4", "repo": "borisyankov/DefinitelyTyped", "ref": "master", "path": "typings", "bundle": "typings/tsd ...

Expanding Your jQuery Library from a Content Delivery Network

As of now, I have a jQuery hosted on my FTP along with other web files. YSlow recommends using a CDN for jQuery. However, I am wondering how I can extend that jQuery. Is it possible to add custom functions to it without being able to edit the original co ...

Start Vue.js development server with SSL enabled (for secure HTTPS serving)

Issue with Development Environment: Recently, I encountered an obstacle related to enforcing HTTPS on external hosts as explained in "Deprecating Powerful Features on Insecure Origins". This problem arose because I have my development setup on my laptop an ...

The password prompt window refuses to align with the center of the screen. This

I've been struggling to position the Javascript popup notification using the width, height, top, and left parameters in the window.open function. No matter what I attempt, it stubbornly remains in the top-left corner. Can someone offer some guidance o ...

Tips on implementing Piwik JavaScript code within app.js on Express

I am trying to implement Piwik tracking on my Express website using JavaScript code. I placed the code in my app.js file but encountered an error. Here is the JavaScript code snippet: <script type="text/javascript"> var _paq = _paq || []; ...

Convert your AS3 code to JavaScript with our specialized compilers

Recently, I came across the AS3 to JS compiler known as Jangaroo. It caught my attention because it seems like a valuable tool that aligns well with my preferences in AS3. Are there any similar compilers out there? Is there another programming language ...

JavaScript and jQuery are lightning fast, especially when the page is reloaded

I am currently working on a responsive website that uses liquid layouts. I have encountered challenges when incorporating images in the design, especially when dealing with different browsers like IE, Firefox, and Chrome. Recently, I faced another issue w ...

Mastering the art of manipulating arrays with jquery

Trying to implement a dynamic search bar feature using jQuery. Here is the code snippet: Fiddle : https://jsfiddle.net/fpLf1to4/ var inputSearch = $('.searchInput').hide(); var searchArray = ['s','e','a',& ...

Looping through an object with AngularJS's ng-repeat

Upon receiving an object as the scope, which has the following structure: The controller function is defined as follows: module.controller('ActiveController', ['$scope','$http', function($scope, $http) { $h ...

Unable to serve static files when using NextJs in conjunction with Storybook

The documentation for Next.js (found here) suggests placing image file paths under the public directory. I have a component that successfully displays an image in my Next.js project, but it doesn't render properly within Storybook. The image file is ...

What are the steps to implementing dependency injections in Angular 2?

I have created an AuthService and I am looking to utilize it across all my components. My goal is to maintain a global userLoggedIn value for all components. However, I encountered the following error when running the script - Property 'userLoggedIn&a ...

Deciphering a JSON array by value or key

I have a JSON array that I need to parse in order to display the available locations neatly in a list format. However, I am struggling with where to start. The data should be converted to HTML based on the selected date. In addition, a side bar needs to s ...

Error: Material-UI prop type validation failed - Please specify either `children`, `image`, `src`, or `component` prop

Despite having an image prop in CardMedia, I kept encountering this error. Here is a snippet of the code: Error description: const Post = ({ post, setter }) => { const classes = useStyles(); return( <Card className={classes.card} ...

PageCallbacks in .NET 1.1

Is it possible to utilize PageMethods in .NET 1.1 for making server-side method calls from the client side? Could you provide a brief explanation on how to use this feature by calling PageMethods.MyMethod(); ? ...

Image uploading in Angular is not compatible with Internet Explorer, however, it functions correctly in Google Chrome

As of now, my implementation has been successful in all browsers except for Internet Explorer 11. Despite being able to successfully upload .jpeg, .jpg, and .png images in Google Chrome, I am facing issues when trying to upload them in IE 11. The code wo ...

Trigger event once item is selected from the jQuery combobox dropdown

I have implemented a custom autocomplete combobox using the jQuery UI library to create text fields with dropdown functionality. This hybrid input allows users to either select an item from the dropdown or enter free text manually. However, I need to trigg ...

Using AJAX and jQuery for database connectivity allows for seamless data retrieval and manipulation

Greetings! I am currently facing an issue with AJAX & JQUERY while trying to access my database. After researching online, I found a script that seemed promising for my problem. However, when I attempted to implement it, I encountered difficulties. Using ...

Prevent submission until all form fields are filled with data

I need help fixing the issue I'm having with disabling the submit button until all input fields have some data. Currently, the button is disabled but remains that way even after all inputs are filled in. What could be causing this problem? $(docume ...