我觉得这里缺少一些简单的东西。我的目标是能够访问服务中的数据(该服务从端点获取数据),但以后能够通过重新对端点执行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 -->


这似乎没有任何意义。如果我在诺言返回后点击window.logService(),则可以清楚地看到数据在正确的位置,但是我的视图不会更新。

最佳答案

即使您重新分配值,Angular也会监视{}引用。

尝试在回调中使用angular.copy(),以便监视的对象得到更新,并且视图正确更新。

.then(function(res) {
    angular.copy( res.data, self.myData);
});

关于javascript - 在Angular中解决 promise 后重新制作请求,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28121652/

10-16 20:03