Request data from another $http request in a different file using synchronous calling

Looking to extract a URL from a JSON file and pass it to another JavaScript file that makes an HTTP GET request to execute the URL. This setup involves using one service within another service file to retrieve data. However, upon running the process, the function bannerslides returns 'undefined'.

File: common.js

(function() {
    angular.module('siteModule')
    .service('loggerService', function ($http, $q) 
    {   var rox;
        var deffered = $q.defer();
         $http.get('/config/config.json').then(function (data)
         {
                deffered.resolve(data);
         });

         this.getPlayers = function ()
            {
                return deffered.promise;
            }
    })
})();

File: siteService.js

(function() {
     var confUrl;
    angular.module('siteModule')
    .service('siteService', function ($http, $q, loggerService) 
    {

         loggerService.getPlayers().then(function (data) {
            confUrl = data.data.baseUrl+data.data.urls.site;
            console.log("GOTURL",confUrl);

         });

        this.bannerSlides = function(){
              console.log("URL NOT GET",confUrl);
             return $http({
                method: "GET",
                dataType: "json",
                url: confUrl
             }).then(function (response) {
                 // inspect/modify the received data and pass it onward
                 return response.data;
             }, function (error) {
 // inspect/modify the data and throw a new error or return data
                 throw error;
             });
        }
  })

})();

Answer №1

It is essential to understand that all $http calls in AngularJS are asynchronous. This means that you must chain your promises together to ensure proper execution. Start by fetching the URL from a JSON file before making the call. In other words, consider moving the loggerService.getPlayers() function inside your this.bannerSlides function.

Before proceeding, take a moment to question why you require $q in your logger service when $http already returns a promise on its own.

Here's an example of the code structure:

(function() {
  angular.module('siteModule')
    .service('loggerService', function($http) {
      this.getPlayers = function() {
        return $http.get('/config/config.json')
      }
    })
})();

Now let's look at another snippet of code:

(function() {
  var confUrl;
  angular.module('siteModule')
    .service('siteService', function($http, $q, loggerService) {
      this.bannerSlides = function() {
        loggerService.getPlayers().then(function(data) {
          confUrl = data.data.baseUrl + data.data.urls.site;
          console.log("GOTURL", confUrl);
          //remember to place your return statement here 
          return $http({
            method: "GET",
            dataType: "json",
            url: confUrl
          })
        });
      }
    })
})();

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

The menu is about to receive some custom styling

I have come across a webpage where I need to make some modifications, but I am unable to locate the script responsible for applying the inline style. This issue only seems to be occurring on the mobile version with the dropdown menu. <div class="is-dri ...

Sort div elements based on checkbox filters

I have a set of checkboxes that I want to use for filtering purposes. <div class="filter"> <div class="checkbox"> <label><input type="checkbox" rel="canada"/>Canada</label> </div> <div class="chec ...

Issue with Jquery function not executing on second attempt

/** Creates a table of iTunes data in HTML format **/ var appendValues = function(songArray) { songArray.each(function() { var title = $(this).find("im\\:name").eq(0).text(); var songImage = $(this).find("im\\:image").eq(0).text(); var ...

iOS Networking - Learning how to manage HTTP connections and background tasks

I created an application that allows users to send messages along with images. Sometimes a user may hit send and then quickly switch to another app or close their phone. We encountered an issue where if there was a poor network connection, the message wou ...

Ways to display or conceal information depending on the dropdown choice

In my Angular project, I am dealing with a dropdown menu that is followed by some data displayed in a div element. component.html <select class="form-control" id="power" required> <option value="" disabled selected ...

Troubleshooting Issue with Public File Serving in ExpressJS Deployment (NodeJS/Express)

The directory structure of my project is organized as follows: my_project server.js app.js | | - public | ----------| images | javascripts | stylesheets | -------------- imgs ---scripts.js ---styles.css | | - routes | | - views | ...

Encounter a Socket.io connection error due to net::ERR_CONNECTION_REFUSED when trying to access from multiple devices

I'm having trouble with other people's computers accessing my test chatting application. When they try to connect, they encounter this error: localhost:3000/socket.io/?EIO=4&transport=polling&t=Oi2Ko0C:1 Failed to ...

How can we smoothly animate scrolling to the top of an element using jQuery?

I am attempting to implement a function where elements scroll to the top with animation upon being clicked. However, I am facing challenges in making this work successfully. You can view my code in action here: https://jsfiddle.net/3dqzsu2m/1/ Here is ...

Removing Items from Orders

Stored in my MongoDB is the following JSON data: [ { "orderItems": [ "606808d2d7351b0c52d38634", "606808d2d7351b0c52d38635" ], "status": "Pending", ...

What is the best way to include a JavaScript function within a JSON file?

I am attempting to transform a JSON file into an object within my application, complete with embedded functions. However, I am facing difficulties in accomplishing this task. The JSON file causing issues is as follows: { "draw": function() { ctx.cle ...

Minimize white spaces when validating input fields in a form using Javascript

I'm currently facing a challenge with JavaScript, specifically regarding achieving five tasks without using jQuery. Despite trying various RegExp codes, none have successfully worked for me so far. Let's begin with the first task (number 1): El ...

The error message "Cannot construct apickli.Apickli" is indicating a Type Error

Encountering this issue : TypeError: apickli.Apickli is not a constructor every time I attempt to execute Sendpostrequest.js again in the following step of a scenario. In A.js, the initial call to Sendpostrequest works without any problems. However, ...

React with Typescript: Issue with mapping array not displaying all elements

I am facing an issue with my Table / Array. If I click on the blue button, all items in the same group as the selected record should have their status changed to "Gratis". However, currently, only the value of the selected record and those above it are cha ...

The onkey_Up function in the HTML textbox is not properly functioning within the ascx control

I attempted to use onkey_up to transfer data from one textbox to another on a user control ascx file, but it is not working when I run it. Could the issue be that I placed the onkey_up function in .ascx instead of the master page? function sync() { ...

Execute a function only once when scrolling

Is there a way to trigger a function only once on scroll event? I have been struggling to achieve this, despite trying different approaches like using .on(), setting a counter, and modifying the code inside/outside the window.scrollstop function. The fun ...

Show the HTTP parameter only if the value is not empty

When developing a React application, I've been using the following code snippet to set a value as a URL path parameter: const [exchangeId, setExchangeId] = useState(''); ..... const endURL = `?page=${paginationState.activePage}&so ...

Could someone break down for me the behavior exhibited within this method?

Hello there, I'm a beginner so please forgive me for any lack of knowledge. const example = { myFunction(){ console.log(this); }, myFunction2(){ function myFunction3(){ console.log(this) } return ...

Having trouble locating the objects in the parent scope of an Angular directive

My custom directive needs to access the object $scope.$parent.users. When I use console.log $scope.$parent: myDirective.directive('scheduleItem', function(){ return { restrict: 'EA', link: function($sco ...

Restart Variable Counter following a new AJAX call in JavaScript/jQuery

I am facing an issue with a page where contents are loaded using AJAX. The main page (index.html) has the following code: <a href="#" id="loadContent">Load Remote Page</a> <div id="ajaxContent"> // Loads AJAX contents Here!! </div& ...

Utilize Vue.js to take screenshots on your device

After following the tutorial at https://www.digitalocean.com/community/tutorials/vuejs-screenshot-ui, I was able to successfully capture a screenshot with Vue.js. However, it seems that the dimensions of the screenshot are not quite right. Issue: The cap ...