AngularJS:$ resource中的拦截器问题

时间:2015-02-26 16:47:11

标签: angularjs angular-resource

我有一个奇怪的行为,通过$ resource使用自定义拦截器操纵响应。

如果我使用这样的响应拦截器:

angular.module( 'app.services', [] )
  .factory( 'Product', function( $resource, routesConfig ) {
      return $resource( routesConfig.catalogueEndPointg(), {}, { 
        query: { 
          method :'GET', 
          isArray : false, 
          params : { 
            page : '@currentPage'
          },
          interceptor: {
            response: function( response ) {
              // DO STUFF
              return response;
            }
          },
        } 
      });
    });

然后,从我的控制器:

angular.module( 'app.controllers', [])
  .controller( 'DummyController', function( $scope, Product ){
    productsPromise.$promise
      .then(
        // Success
        function ( response ) {
          console.log( response );
        });
  }); 

此时,这是console.log(响应)的输出:

enter image description here

在响应对象上,我有预期的数据对象,但我也有这个资源:资源对象,它还包括响应数据。

但是,如果我根本不使用拦截器;我得到了预期的回应:

enter image description here

我不明白这种行为,我担心执行或记忆问题。

有人可以澄清这个吗?

PS:我需要使用拦截器,因为我必须修改服务器的响应。

2 个答案:

答案 0 :(得分:3)

不知道这种行为的原因。

ngResource故意这样做。

1 2

答案 1 :(得分:2)

从github问题中提取 - >由gkalpak回答 - > answer


默认拦截器不会添加任何属性(该属性已经存在,由ngResource添加,原因我很快就会解释)。所有拦截器都返回response.resource而不是responseresponse.data

ngResource"如何运作":

请考虑以下代码:

var User = $resource(...);
var userInstance = User.get({id: 1});
// Request still pending | `userInstance` is an instance of `User`
// ...
// Response arrived | `userInstance` updated with new fields (from `response.data`)

基本上,当您创建资源实例时,User.get()(或您使用的任何方法)将返回一个对象(或isArray: true的数组),这是User的一个实例。 $resource会保留对此返回的userInstance的引用,因此一旦响应到达,它就可以使用更多属性填充它(基本上,它将userInstanceresponse.data一起扩展


为什么ngResource执行此操作

这是ngResource的一个非常方便的功能,允许您在检索需要在视图中显示的数据时避免使用某些样板。比较以下片段:

<!-- In the view -->
Current user: {{ user.username }} &lt;{{ user.email }}&gt;

// Now, you can do this:
$scope.user = User.get({id: 1});

// You DON'T need to do this:
User.get({id: 1}).$promise.then(function (user) {
  $scope.user = user;
});

为什么不直接返回resource

那么,为什么依靠默认拦截器来返回response.resource?为什么不让$resource直接返回resource的地方(而不是将其附加到response)? 这是为了允许您使用可以访问其他与响应相关的数据(例如headersstatus等)的自定义拦截器,而如果您选择不使用,则仍然只返回resource使用自定义拦截器。


PS:离开这里是为了提供答案。也许有人会检查这个。