我觉得我在这里错过了一些简单的东西。我的目标是能够从服务访问数据(从端点获取数据),但稍后能够通过重新 ping 端点来更新存储的数据。
.service('myService', function($http) {
var self = this;
this.myData = {};
this.getItem = function() {
return $http.get('/path/to/endpoint')
.then(function(res) {
self.myData = res.data; // data looks like: { x: 1, y: 2}
});
};
})
.controller('mainCtrl', function($scope, myService) {
myService.getItem();
$scope.data = myService.myData;
window.logService = function() {
console.log(myService); // { getItem: function(){...}, data: {x: 1, y: 2} }
};
});
<div ng-controller="mainCtrl">{{data.x}}</div> <!-- Does not update with the data returned from the promise -->
这似乎没有任何意义。如果我在 Promise 返回后点击 window.logService()
,我会清楚地看到正确位置的数据,但我的 View 不会更新。
最佳答案
即使在您重新分配值后,Angular 也会监视 {}
引用。
尝试在回调中使用angular.copy()
,以便监视的对象得到更新并且您的 View 正确更新。
.then(function(res) {
angular.copy( res.data, self.myData);
});
关于javascript - 在 Angular 中 promise 解决后重新发出请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28121652/