Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs ngResource:自定义更新方法清理实例_Angularjs_Ngresource - Fatal编程技术网

Angularjs ngResource:自定义更新方法清理实例

Angularjs ngResource:自定义更新方法清理实例,angularjs,ngresource,Angularjs,Ngresource,我使用$resource为客户提供此服务: .factory('Customer', function($resource, apiURL){ return $resource(apiURL+'customers/:id', { id: '@id' }, { 'update': {method: 'PUT'} }) }) 当我更新客户(即客户服务的一个实例)时,在承诺得到解决后,客户var将被清除。为什么? $scope.customer = Customer.

我使用
$resource
为客户提供此
服务:

.factory('Customer', function($resource, apiURL){
    return $resource(apiURL+'customers/:id', { id: '@id' }, {
        'update': {method: 'PUT'}
    })
})
当我更新
客户
(即
客户
服务的一个实例)时,在承诺得到解决后,
客户
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 }
        })
});
当我更新客户(这是客户服务的一个实例)时,在承诺得到解决之后,客户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 }
        })
});
$update
解析时,它将清除
$resource
对象,并用新数据更新该对象。您的服务器正在返回空数据

如果要在不清除对象的情况下进行更新,请将更新后的对象放入
Customer.update
方法的第二个参数中

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

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

我已经使用基于json文件的json服务器创建了一个简单的服务:

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

更新

服务上的
PUT
方法不仅应该更新服务器上的customer,还应该返回更新的对象。如果没有,您的$scope.customer将被服务返回的空对象替换