为什么有角服务“私有"?字段不更新? [英] Why do angular service "private" fields not update?

查看:99
本文介绍了为什么有角服务“私有"?字段不更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我遵循这种制造工厂的特殊做法:

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

每一次,每次注入服务,somevalue的值总是被初始化为2,即使我之前已使用UpdateValue方法对其进行了更新.但是,如果我在值上使用getter方法,则该方法将在服务的所有实例中更新.

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/

这里的背景是什么?

推荐答案

如您所知,工厂函数仅被调用一次-angular将返回相同的对象,供控制器中工厂的后续使用.

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

您的小提琴实际上不是在测试somevalue的值-在测试

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

myService.theValue

此属性将在实例化时返回私有变量some​​value 的值,因此在您的示例中它将始终为"2".当somevalue更改时,它不会更改.

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.

吸气剂

myService.getvalue()

在当前时间返回私有变量some​​value的值,因此随着不同的控制器更新该值而改变.

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

这篇关于为什么有角服务“私有"?字段不更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆