如何使用数组更新angularjs.module.value并通过服务检索它?

时间:2017-12-06 15:09:05

标签: angularjs

我试图在一个带有数组的控制器中更新全局angularjs module.value,然后在服务中检索该全局数组。但阵列并不存在。

app.js

  app.factory('featureClaims', function($q) {
    var featureClaims = {};

    featureClaims.init = function() {
        featureClaims.claims = [];
    }
    featureClaims.get = function() {
        return $q.when(featureClaims.claims);
    }
    featureClaims.set = function(data) {
        featureClaims.claims = data;
        return $q.when(featureClaims.claims); // I'm using the $q library to return a promise.
    }
    return featureClaims;
});

的LoginController

let loginController = function($scope, loginService, toastrObj, featureClaims) {
   $scope.login = function(){
            featureClaims.init();
            featureClaims.set(result.data.FeatureClaims); // updating ok here
   }
}

app.controller("loginController", ["$scope", 'loginService', 'toastrObj', 'featureClaims',loginController]);

家庭服务

let homeService= function(featureClaims) {   // featureClaims.claims is null
    return{
        validateUser: function(expectedClaim) {
            if(expectedClaim !== ""){
                featureClaims.get().then(function(data){
                    return data.includes(expectedClaim);  // data is return as undefined
                })
            }

            return false;
        }
    }
};
app.factory('homeService',['featureClaims', homeService]);

1 个答案:

答案 0 :(得分:0)

我认为你不能以这种方式使用价值服务。作者从this post说明:“注意:确保您永远不会覆盖整个值服务/对象,否则您的分配将丢失。始终重新分配值对象的属性值。以下分配是错误的不会导致预期的行为“

相反,为什么不将你的价值转换为这样的工厂:

app.factory('featureClaims', function($q) {
    var featureClaims = {};

    featureClaims.init = function() {
        featureClaims.claims = [];
    }

    featureClaims.get = function() {
        return $q.when(featureClaims.claims); 
    }

    featureClaims.set = function(data) {
        featureClaims.claims = data;
        return $q.when(featureClaims.claims); // I'm using the $q library to return a promise.
    }
    return featureClaims;
});

在您的控制器中:

featureClaims.init();
// you need to wait for the promise to resolve with 'then'
featureClaims.set(['foo', 'bar']).then(function(response) {
   console.log(response); // logs ["foo", "bar"]
});

featureClaims.get().then(function(response) {
   console.log(response); // logs ["foo", "bar"]
});

经过测试和工作。您将需要创建一个只返回数据的get方法,而不是先设置它。