【问题标题】:ngResource: Custom update method cleans the instancengResource:自定义更新方法清理实例
【发布时间】:2016-04-22 05:03:01
【问题描述】:

我用$resource 做这个Customer 服务:

.factory('Customer', function($resource, apiURL){
    return $resource(apiURL+'customers/:id', { id: '@id' }, {
        'update': {method: 'PUT'}
    })
})

当我更新customer这是Customer 服务的实例),并且在promise 被解决后,customer var 被清除.为什么?

$scope.customer = Customer.get({id: $stateParams.id}, function (){
    console.log($scope.customer) // Object {id: 1, name: 'John Doe', ...}
    $scope.customer.$update()
        .then(function () {
            console.log($scope.customer) // Object { status: true, $promise: Object, $resolved: true }
        })
});

【问题讨论】:

    标签: angularjs ngresource


    【解决方案1】:

    我基于 JSON 文件使用json-server (https://github.com/typicode/json-server) 创建了一个简单的服务:

    {
      "customers": [
        {
          "id": 1,
          "name": "John Doe",
          "age": 25
        }
      ]
    }
    

    我还复制粘贴了您的代码(我所做的唯一更改是使用 1 而不是 $stateParams.id)并使用上述服务和 angular-resource v1.4.8 对其进行了测试。没有这样的问题 - 两个控制台日志显示完全相同的输出。也许问题是由服务器端代码引起的?我想不出为什么这在 Angular 中不起作用(旧版本的 angular-resource 除外)。

    更新

    您在服务上的PUT 方法不仅应该更新服务器上的客户,还应该返回更新后的对象。如果不是,您的 $scope.customer 将替换为从服务返回的空对象。

    【讨论】:

      【解决方案2】:

      当我更新客户(即客户服务实例)时,并且在解决承诺后,客户变量被清除。为什么?

      $update 解析时,它会清除并使用新数据更新$resource 对象。您的服务器正在返回空数据。

      如果您想更新而不清除对象,请将更新后的对象放在Customer.update 方法的第二个参数中。

      Customer.update({id: $stateParams.id}, $scope.customer);
      

      或者修改你的服务器以返回更新的信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-19
        • 1970-01-01
        • 1970-01-01
        • 2016-04-24
        • 2012-05-26
        • 1970-01-01
        • 1970-01-01
        • 2016-06-17
        相关资源
        最近更新 更多