2013-10-09 53 views
0

我读了关于restangular的好东西,但我不知道如何从我当前使用$ resource的配置进行切换。

这里与$资源工作的我的实际设置:

的service.js内:

.factory('List', function($resource) { 
    return $resource('relative/url/to/json/:type/:id', { type:'@type', id:'@id' }); 
}) 

两个不同的控制器使用此服务:

• “详细信息” 控制器

.controller('DetailCtrl', ['$scope', '$routeParams', 'List', function($scope, $routeParams, List) { 
    var p = {'type': $routeParams.type, "id": $routeParams.id }; 
    List.get(p, function(detail, responseHeaders) { // success callback 
     $scope.detail = detail; 
     // do something with responseHeaders 
    }); 
}]) 

• “列表” 控制器:

.controller('ListCtrl', ['$scope', 'List', function($scope, List) { 
    var params = { sort: 'DESC', limit: 8 }; 
    $scope.loadList = function (type, params) { 
     params.type = type; 
     List.query(params, function(list, responseHeaders) { // success callback 
      $scope.list = list; 
      // do something with responseHeaders 
     }); 
    } 
}]) 

我想restangular全部更换为$资源的东西。配置后

,Restangular被获取的DATAS的基本途径,是这样的:

• “详细信息” 内部控制

$scope.elm = Restangular.one($routeParams.type, $routeParams.id).get(); 

• “列表” 控制器

var params = { sort: 'DESC', limit: 8}; 
$scope.loadList = function (type, params) { 
    $scope.list = Restangular.all(type).getList(params); 
} 

这是工作。但现在:

1.如何获得响应头?

2.如何将数据发送到成功回调函数内的作用域?

回答

0

嗯,我想对你来说已经太迟了,但也许这可以帮助别人。

对于问题1,我发现这个在restangular github

setFullRequestInterceptor

的fullRequestInterceptor类似于requestInterceptor但 更强大。它允许您更改元素,请求参数 以及标题。

它是一个函数,它接收与req​​uestInterceptor相同的报头和 报头和查询参数(按此顺序)。

它必须返回具有以下属性的对象:

头:标头发送

PARAMS:请求参数发送

元素:元素发送

httpConfig :该httpConfig调用与

你可以做到这一点牛逼他的方式(编辑:我想在此功能,您还可以设置范围的数据,更改代码):

Restangular.setFullResponse(true); 
Restangular.setResponseInterceptor(function (data, operation, what, url, response, deferred) { 
    var contentType = response.headers['Content-Type']; // this to get content-type 
    var status = response.headers['Status']; // here we obtain the http response status 

    // now we can mount our own js object to return all we need 
    // i.e.: the status, content-type and response data to be processed into another function 
    var myArray = [contentType, status, response.data]; 
    // i think we can also set scope data 
    $scope.myData = response.data; 

    return myArray; 
});