0

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

这是我使用 $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替换所有$resource的东西。

配置后,Restangular 以基本方式获取数据,如下所示:

• 在“细节”控制器内部

$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.如何将数据发送到成功回调函数内的范围?

4

1 回答 1

0

好吧,我想对你来说为时已晚,但也许这可以帮助其他人。

对于问题 #1,我在restangular github找到了这个:

setFullRequestInterceptor

fullRequestInterceptor 类似于 requestInterceptor 但更强大。它还允许您更改元素、请求参数和标头。

它是一个接收与 requestInterceptor 相同的函数以及标题和查询参数(按此顺序)的函数。

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

headers:要发送的标头

params:要发送的请求参数

element:要发送的元素

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;
}); 
于 2014-01-17T09:11:18.900 回答