javascript - AngularJS - 使用 $http 更新数组内的嵌套对象属性

标签 javascript arrays angularjs ajax object

我有一个包含对象数组的 JSON 文件。像这样

[
    { "id": 1, "properties": { "name": "Sam", "color": "blue" } },
    { "id": 2, "properties": { "name": "George", "color": "green" } }
];

单击按钮后,我需要更新此文件。我需要更改数组内第一个对象的属性属性内的名称属性。

<button ng-click="updateProperties()">Update Names</button>

我知道解决方案涉及$http

我在想也许可以将 $http-post 方法嵌套在 $http-get 方法中?

$scope.updateProperties = function() {
    $http.get('data.json')
        .then(function(response) {
            var name = response.data[0].properties.name;
            $http.post('data.json') {
                .then(function(response) {
                    response.data[0].properties.name = 'Lucas';
                });
            }
        });

祝你好运!这是一项艰难的任务。

最佳答案

您可能应该采用函数参数。另外,为什么您要在发布后尝试修改它(大概是该帖子更新了服务器)。检索、修改,然后发回服务器。此外,您还应该使用 $http.post() 的参数来发送数据。

angular $http docs

$scope.updateProperties = function() { // Update what with what???  Use one or more arguments?
  return $http.get('data.json')  // You could take the URL as argument
    .then(function(response) {
      response.data[0].properties.name = 'Lucas'; // Maybe use a function argument instead?
      return $http.post('data.json', response.data);
    })
}

关于javascript - AngularJS - 使用 $http 更新数组内的嵌套对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35421698/

相关文章:

asp.net - 在 Javascript 中获取 GridView 选定行的 DataKey

javascript - 选择选项的自定义属性并从 Angular 5 中的 AbstractControl 访问它?

java - 如何声明和调用从 RPG 获取二维 bye 数组参数的 java 方法?

javascript - 如何在没有数学库的情况下在 JavaScript 中 chop 小数?

angularjs - 带有签名 cookie 的 AWS Cloudfront POST 请求

javascript - 从 `array` 中移除 `<select>` 中的元素

javascript - 箭头键在 Firefox 中无法使用给定的 javascript 工作

java - 如何将 BigInteger 与数组一起使用?

c++ - C++中如何改变数组的顺序

javascript - 如何将对象字面量输入 JSON.parse?