Issues related to timing with $http requests in AngularJS

Encountering two issues here. I am attempting to fetch a value from an $http response and store it in a variable that is supposed to update multiple DOM elements. The problem arises when there seems to be a timing issue where the function calling the $http service completes before the variable is updated, causing inconsistencies in the updates across various elements. I also tried using a watch on the variable, but it only triggers when the page is initially loaded. I have spent hours researching on this today, yet haven't found a solution that works.

app.controller('MainCtrl', ['$scope', '$http', 'waciServ', function($scope, $http, waciServ) {
"use strict";
$scope.currentSource = waciServ.activeSource;

$scope.$watch('waciServ.activeSource', function(newValue, oldValue) {
        $scope.currentSource = newValue;
        console.log('Watcher! ' + newValue);
}/*, true*/);

$scope.getActiveSource = function () {
    $scope.currentSource = waciServ.getStringByName("active_device");
};
}]);

app.service('waciServ', function($http) {
  var self = this;
  this.waciIP = location.host;
  this.activeSource = '';

  this.getStringByName = function (name) {
    $http.post("http://" + self.waciIP + "/rpc/", "method=GetVariableByName&param1=" + name + "&encoding=2")
        .then (function (response) {
            var was_error = self.read(response.data);

            if (was_error == '1') { //active_device is not set
                self.assignVariable(name, "none");
                self.activeSource = "none";
                return self.activeSource;

            } else {
                var varId = parseInt(self.read(response.data));
                $http.post("http://" + self.waciIP + "/rpc/", "method=GetVariableValue&param1=" + varId + "&encoding=2")
                    .then (function (response) {

                        self.activeSource = self.read(response.data);

                        return self.activeSource;      
                });
            }
    }, function (error) {
        console.log("error: " + error.data);
    });
  };
});

It's perplexing as I can see the desired result with a console.log right before the return statement, however, another console.log within the controller function displays 'undefined'.

Any insights or solutions would be greatly appreciated. Thank you.

Answer №1

Using a watcher may not be necessary in this case.

The issue lies in the fact that you are not returning a promise from your service method. Ensure that you return promises from the $http method calls within your service method. Then, utilize the .then function to chain promises and include both success and error functions within it. (You can refer to this similar answer for more insights)

Service:

self.fetchDataByName = function(name) {
  // Return promise here
  return $http.post("http://" + self.dataServerIP + "/api/", "method=GetDataByName&param1=" + name + "&encoding=2")
    .then(function(response) {
    var errorCheck = self.parseData(response.data);

    if (errorCheck == '1') { 
      // Handle error scenario
      self.loadData(name, "none");
      self.currentData = "none";
      return self.currentData;
    } else {
      var dataId = parseInt(self.parseData(response.data));
      // Return promise here
      return $http.post("http://" + self.dataServerIP + "/api/", "method=GetDataValue&param1=" + dataId + "&encoding=2")
        .then(function(response) {
        self.currentData = self.parseData(response.data);
        // Return fetched data
        return self.currentData;
      });
    }
  }, function(error) {
    console.log("Error: " + error.data);
  });
};

Controller:

app.controller('MainCtrl', ['$scope', '$http', 'dataService', function($scope,      $http, dataService) {
"use strict";
   $scope.currentData = dataService.currentData;

   $scope.getData = function () {
      dataService.fetchDataByName("selected_data").then(function(data){
         $scope.currentData = data;
      });
   };
}]);

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

Filtering data in VueJs using Vuetify's v-tabs feature

I am currently utilizing NuxtJs, a lightweight version of the VueJS framework. My goal is to implement a data filtering functionality based on tab clicks. The objective is to display the data in alphabetical order and filter them accordingly when tabs are ...

Steps to transfer a JavaScript variable to a PHP session

Currently, I am in the process of retrieving the value of a checkbox and assigning it to a PHP session variable. Below is the relevant portion of the code: The checkbox: $html .= '<span><input type="checkbox" id="checkbox' ...

Executing a NodeJS method from the client side with a button click: A simple guide

I am looking to implement a feature where an image can be downloaded to my server using node js when a button is clicked by the client. I have successfully implemented the backend function, but I am unsure about how to achieve this on the front end. Below ...

JavaScript: End the program upon clicking CANCEL

Scenario: In my application, there is a confirmation pop-up message that appears when I try to save an entry. Clicking the OK button proceeds with saving the entry, while clicking the CANCEL button should go back to the booking content page - this functio ...

Save the value of a promise in a variable for future use in state management within a React-Native application

let storage = AsyncStorage.getItem('@location_data').then(data => data) const MainApp = () => { let [currentLocation, setCurrentLocation] = useState(storage); The current situation is that the storage variable holds a promise. How can ...

An issue occurred: The property 'postFeedback' cannot be read as it is undefined

Version of Angular and Node : Angular CLI: 6.2.9 Node: 8.17.0 An error is being thrown with a stack trace when clicking on the Send Feedback button: ERROR TypeError: Cannot read property 'postFeedback' of undefined at FeedbackComponent.push../ ...

Querying a subarray in MongoDB

Here is a document I have: { "_id" : "someId", "name" : "myTeam", "team" : [ { "entity" : "size", "value" : 14 }, { "entity" : "returns", ...

Missing Cookie in request using NodeJS and NextJS

Struggling with integrating cookies in a fullstack app I'm developing using Node for backend and NextJS for frontend on separate servers. The challenge lies in getting the browser to attach the cookie received in the response header from the node serv ...

Having trouble accessing information from Firebase Realtime Database within a React Native application

I am currently developing a React Native application that interacts with a Firebase database for reading and writing data. I have configured my Firebase permissions to allow read and write access: { "rules": { ".read": true, ...

Retrieving data in [slug].js using Reactjs

I am currently working on a project in Reactjs utilizing the "nextjs" framework. I have successfully managed to retrieve data (specific blog details) based on the slug([slug.js]). However, I now need to display data from all other blogs within the same c ...

Each time the state changes, the array of components is reset

I'm working on a form to create training programs that display a week, starting with an array of all the days. The rendered day depends on the current day (state). The issue is that every time I switch the current day, such as clicking on a different ...

Step-by-step guide on integrating a JSON array fetched via Ajax from a Django/Python view with DataTable

Being a new developer, I am embarking on my first professional project using Django. My main challenge lies in loading data that I have extracted from the models.py into a DataTable within my view.py file. Below is the snippet of my code. Brief Overview ...

Animating a div to glide back and forth in Javascript - with a quirky little 'ear' twist

I am looking to implement a feature that allows me to slide a div left and right. I have successfully achieved this using a button click, as suggested in other posts. However, What I would like to do now is add a small floating 'ear' icon that ...

Passing the unique identifier of a record in NextJS to a function that triggers a modal display

I'm currently facing an issue with my NextJS component that displays a list of people. I have implemented a delete button which triggers a modal to confirm the deletion of a person, but I am struggling with passing the id of the person to be deleted. ...

Tips on displaying a particular JSON attribute?

After starting with a JSON string, attempting to convert it into a JSON object and then trying to print a specific field (such as firstName), I am getting undefined. What could be the issue here? Thank you for your help! var string = '{"firstName ...

Experiencing incorrect outcome when using the Number.isInteger() function in JavaScript

I have been experimenting with the Number.isInteger() method on the Chrome console. After running a for loop and checking the result using console.log(arr);, I noticed that the array only contains a single value of 1, like this: [1]; var arr = [1, 2, 3, ...

Is there a way to find the Nth occurrence of a specific weekday in each month between two given dates using JavaScript?

Within my program, users can set events with start and end dates, as well as the period of repetition: weekly, monthly by date, monthly by weekday, or yearly. Once an event is created, it's stored in the database and displayed on the main calendar pag ...

Is it possible to input text outside of a UL tag?

I am currently exploring the capabilities of framework7 and I have a question regarding placing an input type="text" outside the UL tag. Despite my attempts, the CSS styles are not being applied to the text input field. Any insights on this issue would be ...

Assistance with Javascript and Jquery for Wordpress

Here's a snippet of my JavaScript code: jQuery(document).ready(function() { jQuery.wiseguys(); }); // To safely use the "$" sign, we are using a plugin structure (function($) { // This is the class constructor or "init" function $.wiseguys = fun ...

What is the mechanism behind sprites in three.js?

I've encountered a problem with my scene that includes numerous sprites and results in a poor frame rate. I attempted to improve performance by reducing sprite resolution and adjusting camera limitations for render distance, but unfortunately, it had ...