简体   繁体   中英

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.

.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.

Angular is watching the {} reference even after you reassign the value.

Try using angular.copy() in the call back so the watched object gets updated and your view updates correctly.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM