【问题标题】:AngularJS' $rootScope. Unable to create internal variableAngularJS 的 $rootScope。无法创建内部变量
【发布时间】:2016-12-08 00:14:47
【问题描述】:

我正在使用 $rootScope.requestObj 来存储代表某些过滤器的 key:values 对象。

在我的所有应用程序中 $rootScope.requestObj 都被视为单例,它的行为符合预期。

但是,在调用外部 API 时,我创建了一个接收 $rootScope.requestObj 作为参数的服务。

这是我的代码:

 function requestHandler(obj /*In my controller I am passing $rootScope.requestObj*/) {

        var internal_object = obj;

        console.log('BEFORE FILTER = ', JSON.stringify($rootScope.requestObj));

        Object.keys(internal_object).forEach(function (key) {
            if (key != 'limit' && key != 'offset' && key != 'cities') {
                internal_object[key] = null;
            } else {
                if (key == 'limit') {
                    internal_object[key] = REQUEST_LIMIT.simplyRETS; //outputs 500 that is simplyRETS limit for a request.
                }
            }
        });
        console.log('AFTER FILTER = ', JSON.stringify($rootScope.requestObj));
       //Rest of the code, I basically serialize the internal_object and send it
       //as params of a $http.get request.

如您所见,我将 $rootScope.requestObj 传递给我的 internal_object 我遍历内部对象,从不修改实际的 $rootScope.requestObj。仍然是第一个 console.log 输出:

请注意“maxprice”值。

BEFORE FILTER =  {"type":null,"minprice":null,"maxprice":2,"minbeds":null,"maxbeds":null,"minbaths":null,"maxbaths":null,"minarea":null,"maxarea":null,"limit":500,"offset":0,"cities":"Aventura","q":null}

第二个this =

AFTER FILTER =  {"type":null,"minprice":null,"maxprice":null,"minbeds":null,"maxbeds":null,"minbaths":null,"maxbaths":null,"minarea":null,"maxarea":null,"limit":500,"offset":0,"cities":"Aventura","q":null}

不知何故,在我从 INTERNAL_OBJECT 中删除所有不是限制、偏移或城市的东西的小迭代中,我的 $rootScope.requestObj 更改并输出不同的值。

为了简单起见,这里我只是使用 maxprice 进行测试。我目前正在使用JSON.stringify() 来获取对象价值的标记。

我相信我的 internal_object 和我的 $rootScope.requestObj 对象之间仍然存在某种链接。但是,不知道为什么以及如何避免它。

编辑

我感到困惑的原因是我认为 var internal_object 正在内存中创建新空间。正如解释的那样,它正在创建一个引用。

【问题讨论】:

    标签: javascript angularjs api object angularjs-rootscope


    【解决方案1】:

    实际上,这是预期的行为,当您使用“var internal_object = obj;”时,您将obj的内存引用分配给了internal_object,然后您更改了internal_object的值,即与obj的引用相同。 如果您使用 angular,只需使用“var internal_object = angular.copy(obj);”,这样它就会复制对象,而不是使用相同的内存引用。

    【讨论】:

    • 我简直不敢相信这么简单的事情怎么会吸引我。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    相关资源
    最近更新 更多