Reputation: 509
I'm pretty new with AngularJS and I'm trying to use restangular to call my server Rest API that returns me this json:
{"Users":[{"AN01_ID":1,"AN01_NAME":"cust1","AN01_REF":1,"AN01_ALT":4},{"AN01_ID":2,"AN01_NAME":"cust2","AN01_REF":2,"AN01_ALT":3},{"AN01_ID":3,"AN01_NAME":"cust3","AN01_REF":3,"AN01_ALT":2},{"AN01_ID":4,"AN01_NAME":"cust4","AN01_REF":4,"AN01_ALT":1}],"ResponseStatus":{}}
from what I've read in the docs I need to set the addResponseInterceptor
in config
to extract the array I need from my json response like this:
var app = angular.module('testApp', ['restangular']);
app.config(function(RestangularProvider) {
RestangularProvider.setBaseUrl('http://myserver/api/');
RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
return data.Users;
});
});
app.controller('usersController', function($scope, Restangular) {
$scope.users = Restangular.all('users.json').getList().$object;
});
My question is: if I need to specify a different array name for each controller, how can I define the addResponseInterceptor
in my controllers (or alternatively: how can I extract specific array in my controllers)?
Upvotes: 0
Views: 1000
Reputation: 5857
This is not the common way of using responseInterceptor
, you should do some generic things in interceptor like some attribute you want to put every response.
For extracting specific response you should always use promise callback and resolve response in your then block, so this should be your code.
var app = angular.module('testApp', ['restangular']);
app.config(function(RestangularProvider) {
RestangularProvider.setBaseUrl('http://myserver/api/');
// remove this part of the code as you do not need it
});
app.controller('usersController', function($scope, Restangular) {
Restangular.all('users.json').getList().then(function(response){
$scope.users = response.Users;
});
});
Upvotes: 1