我有一个服务获取项由$http
。在控制器中,我与视图共享这些数据。它可以工作,但是当我通过$http
删除或添加新项目时,我无法使我的列表保持最新。
我创建了一个refresh()
函数,我在每次添加或删除一个项目时调用它,但是刷新只在时应用。虽然函数总是被适当地调用和执行,但并不是每次操作都这样。
我应该如何在每次操作时刷新我的项目?
:
refresh = function() {
itemsService.getItems().then(function(d) {
$scope.items= d;
});
}
:
app.factory('itemsService', function($http) {
var itemsService = {
getItems: function() {
return $http.get('items.json')
.then(
function (response) {
return response.data;
}
);
}
};
return itemsService;
});
我也读过关于$watch()
,并试图使其在这种情况下工作,但它似乎没有任何区别:
$scope.$watch('itemsService.getItems()', function(d) {
$scope.items = d;
}, true);
这可能是您正在寻找的Angular JS -监听或绑定$http请求
你可以在请求结束时调用你的函数。
你可以使用一个拦截器来做这件事
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);
});