[英]Remake request after promise resolves in Angular
I feel like I'm missing something simple here. 我觉得这里缺少一些简单的东西。 My goal is to be able to access data from a service (which gets data from an endpoint) but later be able to update that stored data by re-pinging the endpoint.
我的目标是能够访问服务中的数据(该服务从端点获取数据),但以后能够通过重新对端点执行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 -->
This seems to make no sense. 这似乎没有任何意义。 If I hit
window.logService()
after the promise returns, I clearly see the data in the correct spot, yet my view will not update. 如果在诺言返回后点击
window.logService()
,则可以在正确的位置清楚地看到数据,但视图不会更新。
Angular is watching the {}
reference even after you reassign the value. 即使您重新分配值,Angular也会监视
{}
引用。
Try using angular.copy()
in the call back so the watched object gets updated and your view updates correctly. 尝试在回调中使用
angular.copy()
,以便观察的对象得到更新,并且视图正确更新。
.then(function(res) {
angular.copy( res.data, self.myData);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.