Why do angular service “private” fields not update?

╄→гoц情女王★ 提交于 2019-12-12 10:05:29

问题


If I follow this particular practice of making factories:

    myApp.factory('myService', function () {
        var somevalue = 2;

        var myServiceApi = {
            theValue: somevalue,
            updatevalue: updateValue
        }

        return myServiceApi;

        function updateValue(newValue) {
            somevalue = newValue;
        }
    });

Each and every time the service is injected the value of somevalue is always initialized as 2, even though I have updated it earlier with the UpdateValue method. if I however use a getter method on the value it is update in all instances of the service.

http://jsfiddle.net/IngoVals/hd1r1bmp/

What is going on in the background here?


回答1:


As you know, factory functions are only called once - angular will return the same object for subsequent usages of the factory in your controllers.

Your fiddle isn't actually testing the value of somevalue - it's testing the value of

myService.theValue

This property will return the value of the private variable somevalue at the time of instantiation, so it will always be "2" in your example. It does not get changed when somevalue changes.

The getter

myService.getvalue()

returns the value of the private variable somevalue at the current time, so it changes as different controllers update the value.

myApp.factory('myService', function () {
    var somevalue = 2;

    var myService = {
        //equivalent to theValue: 2
        theValue: somevalue,
        updatevalue: updateValue,
        getvalue: getValue
    }

    return myService;

    function getValue() {
        return somevalue;
    }

    function updateValue(newValue) {
        somevalue = newValue;
    }
});



回答2:


someValue is initialized only once and properly updated when updateValue() is called.

myServiceApi.theValue is set once and never changes.

var somevalue = 2;

var myServiceApi = {
      theValue: somevalue,

means create an object and set the property theValue to whatever value somevalue has, in this case 2. There is no connection between theValue and somevalue. And since you never change theValue it's always 2.

Furthermore there is only one instance of myServiceApi. The same instance is used by all controllers.




回答3:


Problem is this var somevalue = 2;

That's a controller variable, I believe you need it to make it a controller $scope variable: $scope.somevalue = 2; That way it's updatable from other Controllers / Services etc.

I like to write $scope variables like this to cut down on characters and also be more readable:

var vs = $scope;
    vs.myVar   = '',
    vs.value   = '',
    vs.myBool  = true,
    vs.myArray = [];

vs.myFunc = function() {
    console.log(vs.value);
};


来源:https://stackoverflow.com/questions/29880592/why-do-angular-service-private-fields-not-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!