【发布时间】:2016-12-12 06:43:48
【问题描述】:
有两个问题。我试图从 $http 响应中获取一个值并用它填充一个变量,然后应该更新几个 DOM 对象。问题是它似乎存在时间问题,其中调用 $http 服务的函数完成,然后变量得到更新,但似乎没有在任何地方更新它应该更新。我还尝试在变量上放置一个手表,它似乎只在页面最初加载时触发。我整天都在阅读这些内容,但似乎找不到有效的答案。
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);
});
};
});
我可以在返回触发之前放置一个console.log,看看我有我想要的,但另一个console.log放在控制器内的函数中显示'未定义'。
什么给了?提前谢谢你。
【问题讨论】:
标签: javascript angularjs promise angular-promise angularjs-http