简体   繁体   English

Angular ngResource $ save方法清除$ resource对象

[英]Angular ngResource $save Method Clears $resource Object

Using Angular 1.5.5 here: 在此处使用Angular 1.5.5:

Is there any way to tell Angular to ignore response body for particular requests (such as $save)? 有什么办法告诉Angular忽略特定请求的响应主体(例如$ save)? It drives me crazy that after I call $save, angular updates the model with the object returned by a server, which initially was supposed to be used to distinguish between different resolutions of the request. 令我发疯的是,在我调用$ save之后,使用服务器返回的对象对angular进行了模型更新,该对象最初被用来区分请求的不同分辨率。 It results in unwanted form clear. 这会导致不需要的表格清晰。 Interestingly enough, this behaviour remains even if I send a 400 or 500 http status code. 有趣的是,即使我发送了400或500个http状态代码,此行为仍然存在。

In case you need more info, relevant code is below. 如果您需要更多信息,请参见下面的相关代码。

Controller: 控制器:

  'use strict';
  angular
    .module('app.operators')
    .controller('OperatorNewController', OperatorNewController);

  OperatorNewController.$inject = ['operatorsService', 'notify'];

  function OperatorNewController(operatorsService, notify) {
    var vm = this;
    vm.done = done;

    activate();

    function activate() {
      vm.operator = new operatorsService();
    }

    function done(form) {
      if (form.$invalid) {
        // do stuff
        return false;
      }

      vm.operator.$save(function(response) {
        if (response.success && response._id) {
          $state.go('app.operators.details', {id: response._id}, { reload: true });
        } else if (response.inactive) {
          // do stuff
        } else {
          // do other stuff
        }
      }, function (error) {
        // do other stuff
      });
    }
  }

Service: 服务:

  'use strict';
  angular
    .module('app.operators')
    .service('operatorsService', operatorsService);

  operatorsService.$inject = ['$resource'];

  function operatorsService($resource) {
    return $resource('/operators/:id/', {id: '@_id'}, {
      'update': { method: 'PUT' }
    });
  }

Server request handler is also fairly simple: 服务器请求处理程序也相当简单:

  .post('/', function (req, res) {
    if (!req.operator.active) {
      return res.status(500).json({ inactive: true, success: false });
    }
    // do stuff
    return res.json({ success: true });
  });

In either way I don't like the idea of having to send the entire object from server (particularily when it's a failed request), and even if I have to, I still need a way to send some extra data that will be ignored by Angular. 无论哪种方式,我都不喜欢必须从服务器发送整个对象的想法(尤其是在请求失败时),即使我必须这样做,我仍然需要一种方法来发送一些额外的数据,这些数据将被忽略。有角度的。

Your help is very much appreciated! 非常感激你的帮助!

The $save method of the resource object empties and replaces the object with the results of the XHR POST results. 资源对象的$save方法清空并用XHR POST结果的结果替换该对象。 To avoid this, use the .save method of the operatorsService : 为了避免这种情况,请使用operatorsService.save方法:

  //vm.operator.$save(function(response) {
  vm.newOperator = operatorsService.save(vm.operator, function(response),
    if (response.success && response._id) {
      $state.go('app.operators.details', {id: response._id}, { reload: true });
    } else if (response.inactive) {
      // do stuff
    } else {
      // do other stuff
    }
  }, function (error) {
    // do other stuff
  });

UPDATE 更新

It results in unwanted form clear. 这会导致不需要的表格清晰。 Interestingly enough, this behaviour remains even if I send a 400 or 500 http status code. 有趣的是,即使我发送了400或500个http状态代码,此行为仍然存在。

This behavior is NOT VERIFIED. 此行为未得到验证。

I created a PLNKR to attempt to verify this behavior and found that the $save method does not replace the resource object if the server returns a status of 400 or 500. However it does empty and replace the resource object if the XHR status code is 200 (OK). 我创建了一个PLNKR来尝试验证此行为,发现如果服务器返回状态400或500,则$save方法不会替换资源对象。但是,如果XHR状态代码为200,则它会清空并替换资源对象。 (好)。

The DEMO on PLNKR PLNKR上演示


It drives me crazy that after I call $save , angular updates the model with the object returned by a server 我打电话给$save之后,我用服务器返回的对象对angular进行了模型更新,这使我发疯

It helps to understand how browsers handle traditional submits from forms. 它有助于了解浏览器如何处理来自表单的传统提交。

The default operation for a submit button uses method=get . 提交按钮的默认操作使用method=get The browser appends the form inputs to the URL as query parameters and executes an HTTP GET operation with that URL. 浏览器将表单输入附加到URL作为查询参数,并对该URL执行HTTP GET操作。 The browser then clears the window or frame and loads the results from the server. 然后,浏览器清除窗口或框架并从服务器加载结果。

The default operation for method=post is to serializes the inputs and place them in the body of an HTTP POST. method=post的默认操作是序列化输入并将其放置在HTTP POST的正文中。 The browser then clears the window or frame and loads the results from the server. 然后,浏览器清除窗口或框架并从服务器加载结果。

In AngularJS the form directive cancels the browser default operation and executes the Angular Expression set by either the ng-submit or ng-click directive. 在AngularJS中, form指令取消浏览器的默认操作,并通过ng-submitng-click指令执行Angular Expression集。 All $resource instance methods including $get and $save , empty and replace the resource object with XHR results from the server if the XHR is successful. 如果XHR成功,则所有$resource实例方法(包括$get$save清空并用服务器的XHR结果替换资源对象。 This is consistent with the way browsers traditionally handle forms. 这与浏览器传统上处理表单的方式一致。

In RESTful APIs, HTTP GET operations return the state of a server resource without changing it. 在RESTful API中,HTTP GET操作返回服务器资源的状态而不更改它。 HTTP POST operations add a new resource state to the server. HTTP POST操作将新的资源状态添加到服务器。 APIs usually return the new resource state, with additional information such as ID, Location, timestamps, etc. Some RESTful APIs return a redirect (status 302 or 303) in which case browsers transparently do an HTTP GET using the new location. API通常返回新的资源状态,以及其他信息,例如ID,位置,时间戳等。某些RESTful API返回重定向(状态302或303),在这种情况下,浏览器会使用新位置透明地执行HTTP GET。 (This helps to Solve the Double Submission Problem .) (这有助于解决双重提交问题 。)

When designing RESTful APIs, it is important to understand how traditional browsers behave and the expectations of RESTful clients such as AngularJS ngResource. 在设计RESTful API时,了解传统浏览器的行为方式以及RESTful客户端(例如AngularJS ngResource)的期望非常重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM