繁体   English   中英

更改从服务返回的数据也会更改服务中的数据

[英]Changing data returned from service changes data in service too

当我将从服务返回的数据存储在控制器中然后进行编辑时,它还会更改服务中的数据。

JSFiddle演示

 /* The backend connection part and the actual markdown editor JS have been removed because it would just make the code huge and is irrelevant to the problem */    

var myApp = angular.module('myApp', []);

// In my app, this service caches blog post data from my server on the client side and returns single posts from it
myApp.factory('PostService', function ($log, $filter, $http) {
    var data;

    // Just an example for data pulled from server
    data = [{
        id: 99999,
        text: "Hello"
    }];

    // Function for returning a post out of the data array loaded from the server
    var getData = function (id) {
        if (id !== undefined) {
            var arr = $filter('filter')(data, {
                id: id
            });
            if (arr.length === 0) {
                $log.error('PostService:: getData(' + id + '):: Post Not Found');
                return 'not_found';
            } else {
                $log.debug('PostService:: getData(' + id + '):: Post returned');
                return arr[0];
            }
        } else {
            return data;
        }
    };
    return {
        getData: getData            
    };
});

function ctrl($log, $scope, PostService) {
    var edit = this;

    // Sample post id
    edit.editingId = 99999;

    // "Copy" (apparrently more "bind") the blog post data to edit.data
    edit.data = PostService.getData(edit.editingId);

}

用于降价编辑器。 我想将服务中的数据加载到控制器中,然后对其进行编辑,然后按“保存”按钮为服务提供新版本。 如果上述行为在Angular的数据绑定意义上是正确的,那么实现我想要的更好的解决方案是什么?

更新资料

基于PSL的注释和Thibaud Sowa的回答,我更改了getData()函数以使用angular.copy()返回副本。 但是,似乎不可能从数组中复制一个对象(例如angular.copy(arr[0]) ),因为它仍将返回整个数组。 请参阅更新的JSFiddle

更新2

好吧,我很傻。 在小提琴中纠正了它。 谢谢您的回答。

这是因为您要返回一个对象。 在javascript中,执行此操作就像传递指针一样。

您应该使用angular.copy逐字段复制对象,如下所示:

        return angular.copy(data);

在此处查看文档https://docs.angularjs.org/api/ng/function/angular.copy

回应您的更新

好吧,我编辑了您的小提琴,以向您展示可以复制数组中的一个项目。 实际上,似乎所有事情都可以按照您的意愿进行……(或者我不理解您的需求!)

更新的小提琴:

https://jsfiddle.net/thibaudsowa/aybLwa2L/3/

有一个非常简单的解决方案来解决您的问题:

如果您不想更改从服务获得的数据,请进行复制

SO上有很多线程讨论快速复制Javascript对象的斋戒或最优雅的方法。 一个简单而快速的解决方案是使用json parse和stringify,如下所示:

var copyOfA = JSON.parse(JSON.stringify(a));

将此应用到您从服务中获得的数据,就可以了:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM