I have a service getting items by $http
. In the controller I share this data with the view. It works, but when I delete or add new items by $http
, I cannot get my list to stay up to date.
I created a refresh()
function, that I call every time I add or delete an item, but the refresh applies only from time to time. And not on every action though the function is always duly called and executed.
How should I proceed to get my items refreshed on every action?
Function:
refresh = function() {
itemsService.getItems().then(function(d) {
$scope.items= d;
});
}
Service:
app.factory('itemsService', function($http) {
var itemsService = {
getItems: function() {
return $http.get('items.json')
.then(
function (response) {
return response.data;
}
);
}
};
return itemsService;
});
I have also read about $watch()
and tried to make it work in this case, but it does not seem to make any difference:
$scope.$watch('itemsService.getItems()', function(d) {
$scope.items = d;
}, true);
This might be what you are looking for Angular JS - listen or bind $http request
You can just call your function when the request ends.
You can use an interceptor to do this
var httpinterceptor = function ($q, $location) {
return {
request: function (config) {
//show your loading message
console.log(config);
return config;
},
response: function (result) {
//hide your loading message
console.log('Repos:', result);
return result;
},
responseError: function (rejection) {
//hide your loading message
console.log('Failed with', rejection);
return $q.reject(rejection);
}
}
};
app.config(function ($httpProvider) {
$httpProvider.interceptors.push(httpinterceptor);
});