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¶m1=" + 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¶m1=" + 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.