Jahongir Rahmonov Jahongir Rahmonov - 6 months ago 8
AngularJS Question

Controller method using old response from service promise after first time in AngularJS

I have this function inside my controller:

function getNewNotifications() {
NotificationService.getNotifications('new')
.then(function (response) {
console.log("in controller: ", response.results);
vm.notificationCount = response.count;
},function (err) {
console.log(err);
});
}


here is the
getNotifications
method of
NotificationService
:

function getNotifications(status) {
var thisUrl = url + '?status=' + status;

$http.get(thisUrl)
.success(function (data) {
console.log("in service: ", data.results);
deferer.resolve(data);
})
.error(function (data) {
deferer.reject(data);
});

return deferer.promise;
}


Both of them log results in their success methods.

I call the controller function like this:

setInterval(getNewNotifications, 5000);


i.e. it gets new notifications every five seconds!

The first time the controller method is called, the browser logs are:

in service: Object
in controller: Object


As expected! However, after this, the order is reversed:

in controller: Object
in service: Object


This is weird and leading to other problems.

Why is this happening and how can I prevent it?

Answer

If the promise is created outside the getNotifications function it will already be resolved the second time the function is called, and the data from the first call will be returned again.

You simply need to recreate a new promise each time getNotifications is called.

Comments