【问题标题】:$resource Custom Action Replaces my Scoped Variable with the Server Response$resource 自定义操作将我的作用域变量替换为服务器响应
【发布时间】:2013-11-06 03:56:35
【问题描述】:

我正在使用带有自定义操作的 $resource。

myApp.factory('User', [ '$resource', function($resource)
{
    return $resource('/QuantumServer/users/:id.json',
    {
        id : '@id'
    },

    {
        resetPassword :
        {
            method : 'POST',
            url : '/QuantumServer/users/:id/resetPassword.json'
        }
    });
} ]);

我可以毫无问题地检索我的用户对象。问题是当我调用自定义操作时,我的本地范围用户对象的值被服务器响应替换。这是一个问题,因为服务器响应是 { success : true },这会导致我的本地对象丢失其所有字段值。

$scope.resetPassword = function()
{
    $scope.userBeingEdited.$resetPassword(
    {}, function(value, responseHeaders)
    {
        alert('Password reset');

        // The value of $scope.userBeingEdited has been replaced with the
        // server response - how to stop this from happening?
    });
};

我知道 RESTful 哲学指出,例如对资源的 POST 将更新该资源(在服务器上),然后返回更新资源的副本。我知道这就是 AngularJS $resouce.$save 的工作原理。但它真的必须适用于我的自定义操作吗?

【问题讨论】:

  • stackoverflow.com/a/18665982/226513 声明只需将 isArray : True 添加到 resetPassword 自定义操作定义中即可阻止服务器覆盖本地对象。我没有让它工作,因为它只会导致 JavaScript 错误。

标签: angularjs angularjs-resource


【解决方案1】:

这是我知道的一种解决方法,它会导致对象的 副本 被更新,然后我们将其丢弃。这是最优雅的方式吗?

$scope.resetPassword = function()
{
    angular.copy($scope.userBeingEdited).$resetPassword(function(value, responseHeaders)
    {
        alert('Password reset');
    });
};

【讨论】:

    猜你喜欢
    • 2014-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多