如何引用Angular Service返回的数组,以便维护状态

How to reference array returned by Angular Service, in order to maintain state?

本文关键字:数组 状态 维护 返回 Service 何引用 引用 Angular      更新时间:2023-09-26

我有一个名为"categories"的主对象,它由DataService返回,并由许多不同的控制器调用。

.service('DataService', ['$http', '$q', '$timeout', function($http, $q, $timeout) {
    var categories = {};
    // Return public API.
    return({
        setCategory: setCategory,
        getCategory: getCategory
    });
    function setCategory(activities, details) {
        var name = details.shortName,
            category = {};
        category.activities = activities;
        category.details = details;
        categories[name] = category;
    }
    function getCategory(name) {
        return categories[name];
    }

从控制器访问categories以保持所有控制器之间的状态的正确方式是什么?

例如,在Controller1中,我想获取与name匹配的categories对象属性,然后向其中包含的活动添加新值:

$scope.category = getCategory(name);
$scope.category.activities[2].input = true;

然后,我希望能够在任何使用getCategories服务的地方访问category.activities[2].input的值。但据我所知,这行不通,因为我已经将categories[name]重新分配给了$scope.category,对吧?

或者,我错了,或者采取了完全错误的方法?从categories对象调用对象的最佳方式是什么,这样我就可以在所有控制器中保持状态?

请不要使用$broadcast。使用$watch

.value('categories',{})
.service("myService",function(categories,$rootScope) {
   $rootScope.$watch(function(){
      return categories;
   },function(val){
      console.log("Some controller, any controller, has updated categories!");
   },true);
})

作为一个建议,您可以在每次控制器进行更改时调用DataService.setCategory。然后,您可以使用$broadcast发送服务已更改的消息,并使用$on订阅和触发"getCategory"方法的刷新,以便在每个控制器中都有最新的型号。

例如,在您的服务中:

.service('DataService', ['$rootScope', '$http', '$q', '$timeout', function($rootScope, $http, $q, $timeout) {
    function setCategory(activities, details) {
        var name = details.shortName,
        category = {};
        category.activities = activities;
        category.details = details;
        categories[name] = category;
        $rootScope.$broadcast('categories:updated');
    }

在控制器中:

.controller('ControllerOne', ['$scope', '$rootScope', 'DataService', function($scope, $rootScope, DataService) {
    $scope.category = DataService.getService(name);
    $scope.category.activities[2].input = true;
    DataService.setCategory(category.activities, category.details);
}])
.controller('ControllerTwo', ['$scope', '$rootScope', 'DataService', function($scope, $rootScope, DataService) {
     $scope.category = DataService.getCategory(name);
     $scope.$on('categories:updated', function(){
         $scope.category = DataService.getCategory(name)             
     });
}]);