用户Angular资源服务$ save函数的正确方法

时间:2013-11-07 15:03:17

标签: php angularjs angularjs-resource

我正在使用角度资源尝试使用角度$ save函数。

默认情况下,$ save将模型发送回服务URL。但是,看起来它希望模型返回到服务(如果我不这样做,我的模型是空的)。我想知道将消息和错误返回给控制器的最佳方法是什么。

我的解决方案是在我的PHP中创建一个新类,它有一个errors数组,用于存储处理过程中遇到的任何错误,以及一个存储模型以便返回的字段。然后在回调函数中发回并处理:

$scope.ApplyChanges=function(){
   console.log("saving...");
    $scope.user.$save(function(data){
      console.log(data);
      if (data.errors.length>0){
         for (error in data.errors){
            $scope.alerts.push({type:'danger', msg: data.errors[error].msg});
         }
         $scope.user=User.get({id:data.data.UserName});
      } else {
         $scope.user=User.get({id:data.data.UserName});
         $scope.alerts.push({type:'success', msg: "User data saved successfully"});
      }
    }, function(err){
         $scope.alerts.push({type:'danger', msg: "There was a problem saving your data: " + err});
    });

这些行:$scope.user=User.get({id:data.data.UserName});我必须使用,因为如果我刚刚将$scope.user分配给data.data,则用户不再使用该服务,当我尝试时我会收到错误再次ApplyChanges

那么,有没有办法更无可救药地做到这一点?因为它是我必须额外回电来获得模型。我是否应该仅在出现错误时发送错误,然后再进行回调以获取模型?还有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

首先,您的服务器应返回相关HTTP error status codes的错误(请参阅4xx和5xx代码)。这样,您只处理错误回调中的错误:

function onError (response){
    switch (response.status) {
    case 400:
    case 404:
    //etc... 
        response.data.errors.forEach(function(error){
            $scope.alerts.push({type:'danger', msg: error.msg});
        });
        break;
    case 500:
        $scope.alerts.push({type:'danger', msg: "There was a problem saving your data: " + response.data});
        break;
    }
}

也就是说,如果$ scope.user是$resource instance,那么你不必从服务器再次获取它,$ save()方法不会改变对象。

要将从服务器检索到的'user'对象中的值复制到$ scope.user,请使用angular.extend()

angular.extend($scope.user, data) //this updates $scope.user with data attributes.

值得注意的是angular.extend如果不需要执行深层复制,请使用jQuery.extend

jQuery.extend(true, $scope.user, data)