如何使用JavaScript或AngularJS保存JSON文件?

3

我本地存储了一个json文件,正在使用它,但是无法保存,失去了持久性。这段代码在我的Web控制器(angularjs)中。

$http.get("users.json")
            .then(function(res) {
                $scope.users = res.data;
            });

        $scope.addUser = function() {
            $scope.users.push({
                name: $scope.user
            });

            $scope.user = "";            
        }

        $scope.removeUser = function() {
            $scope.users.pop({
                name: $scope.user
            });

            $scope.user = "";            
        }

我知道另一种方法是本地存储,但我不能使用它,因为我无法在我的HTML代码中列出每个对象(它说我不能在未定义的对象中推送或弹出)。
那么,我该怎么办呢?
谢谢!

无法从浏览器保存到文件。localStorage 以字符串形式存储,因此不清楚您尝试对其进行 push 的操作。但是,您可以轻松地将数据转换为字符串并在工作时解析回数组/对象。 - charlietfl
1
JSON.stringify(dataObject) 是你的好朋友,然后使用 JSON.parse(dataAsString) 将其转换回来。 - primavera133
3个回答

2

我认为,在调用HTTP请求之前,您需要初始化用户变量。

$scope.users = [];
$http.get("users.json")
        .then(function(res) {
            $scope.users = res.data;
        });

希望它能解决未定义对象问题。


不需要...在回调函数中重新分配会破坏原始引用 - charlietfl
没错,@charlietfl,我在这里试图解释他遇到的“未定义对象”错误,可能是因为他在http请求完成之前尝试了addUser和removeUser操作。 - sushilprj

0
我知道另一种方法是本地存储,但我无法使用它,因为我不能在我的HTML代码中列出每个对象(它说我不能推入或弹出未定义的对象)。
如果您检查数据是否可用,然后添加数据,则可以使用它。另一个选择是,如果用户数据将用于不同页面或控制器,则可以使用$rootScope
在下面的代码中,您没有定义$scope.users,这将引发错误。
// $scope.users = [];  // Uncomment code if variable is not defined
// $scope.user = '';  //  Uncomment code if variable is not defined
$http.get("users.json")
     .then(function(res) {
        $scope.users = res.data;  // Throws error if not defined earlier
});

$scope.addUser = function() {
  $scope.users.push({
    name: $scope.user   // Here $scope.user throws error if not defined earlier
  });

  $scope.user = "";
};

如果您在Angular中使用本地存储,请确保您可以通过使用像https://github.com/grevory/angular-local-storage这样的服务来模拟测试。 - primavera133

0

感谢大家,最终我使用解析和字符串化的 JSON 文件将数据保存在本地存储中了!

$scope.addUser = function() {
    var jsonData = [];

    if (localStorage.getItem("users")) {
        jsonData = JSON.parse(localStorage.getItem("users"));
    }

    jsonData.push ({
        name: $scope.user
    });

    localStorage.setItem("users",JSON.stringify(jsonData));
    $scope.users = jsonData;
    $scope.user = "";            
}

$scope.removeUser = function(user) {

    if (localStorage.getItem("users")) {
        jsonData = JSON.parse(localStorage.getItem("users"));
    }

    for (var index in jsonData) {
        if (jsonData[index].name === user.name) {
            jsonData.splice(index,1);
        }
    }

    localStorage.setItem("users",JSON.stringify(jsonData));
    $scope.users = jsonData;
    $scope.user = "";            
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接