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

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

问题描述

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

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

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

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

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

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