AngularJS: 刷新服务结果

AngularJS: Refreshing service result

我有一项服务通过 $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);

这可能就是您要找的

您可以在请求结束时调用您的函数。

你可以使用拦截器来做到这一点

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);

});