【问题标题】:Proper way to user Angular resource service $save function使用 Angular 资源服务 $save 功能的正确方法
【发布时间】:2013-11-08 01:12:26
【问题描述】:

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

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

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

$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 时会出现错误。

那么,有没有办法更顺畅地做到这一点?因为它是我必须打一个额外的电话来获取模型。我是否应该仅在出现错误时才发送错误,然后再通过额外的回调来获取模型?有没有更好的办法?

【问题讨论】:

  • 想解释否决票?

标签: php angularjs angularjs-resource


【解决方案1】:

首先,您的服务器应该返回带有相关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() 方法不会更改对象。

要将从服务器检索到的“用户”对象中的值复制到 $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)

【讨论】:

  • 也许我应该更具体一点,如果出现用户输入错误,并且我的服务器端验证出于某种原因将其退回,因此调用成功,但用户没有。
  • 另外,我注意到如果我不将对象返回到保存函数,那么模型就会被清空。
  • 如果服务器端验证失败,则服务器应响应 422 Unprocessable Entity 或 409 Conflict 或相应的状态代码,并在有效负载中包含错误数据。
  • 您使用的是哪个版本的 Angular?我在 1.2.0-rc3 中使用了 $resource,它并没有改变模型。如果您需要将从服务器检索到的“用户”对象中的值复制到 $scope.user,那么您可以使用 angular.extend angular.extend($scope.user, data.data)
  • 我使用的是 1.2.0-rc3。有点不相关,但是是的,每次调用 $save 我的资源都会被清除。我会试试扩展。我的目标是发送关于失败原因的详细消息,尽管 422 错误确实有道理,因为他们会试图绕过我的 api 来惹我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-20
  • 2013-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-19
  • 1970-01-01
相关资源
最近更新 更多