Alexe Bogdan
Web Developer, JavaScript Lover, User Experience Professional, working in the web and mobile application development industry.
$http({method: 'GET', url: '/someUrl'})
.success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
})
.error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise with two $http specific methods: success and error.
*Since the returned value is a promise, you can also use then() for registering callbacks.
$http.get
$http.head
$http.post
$http.put
$http.delete
$http.jsonp
$http.patch
The $http service will automatically add certain HTTP headers to all requests.
The default headers can be fully configured by accesing the $httpProvider.defaults.headers configuration object which contains:
* To add headers for an HTTP method other than POST, PUT or PATCH, simply add a new object:
$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }
Both requests and responses can be transformed using transform functions. By default, Angular applies these transformations:
Request transformations:
- If the data property of the request configuration object contains an object, serialize it into JSON format.
Response transformations:
- If XSRF prefix is detected, strip it (see Security Considerations section below).
- If JSON response is detected, deserialize it using a JSON parser.
//Add a new function at the end of chain
$httpProvider.defaults.transformResponse.push(function(data, headersGetter){
//data it's already converted from an angular default transformer
data.total = headersGetter('X-Total-Count');
return data;
});
//Replace the entire chain
$httpProvider.defaults.transformResponse = [function(data, headersGetter){
//assume the data is a JSON string
var tranformedData = angular.fromJson(data);
tranformedData.total = headersGetter('X-Total-Count');
return tranformedData;
}];
An interceptor is a service factory that is registered with the $httpProvider by adding him to the $httpProvider.interceptors array. The factory is called and injected with dependencies (if specified) and returns the interceptor.
There are two kinds of interceptors (and two kinds of rejection interceptors):
// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
// optional method
'request': function(config) {
// do something on success
return config;
},
// optional method
'requestError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
},
// optional method
'response': function(response) {
// do something on success
return response;
},
// optional method
'responseError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('myHttpInterceptor');
// alternatively, register the interceptor via an anonymous factory
$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
return {
'request': function(config) {
// same as above
},
'response': function(response) {
// same as above
}
};
});
A factory which creates a resource object that lets you interact with RESTful server-side data sources.
Usage: $resource(url, [paramDefaults], [actions]);
//Resource Constructor provided by $resource factory
var User = $resource('/user/:id', {id:'@id'});
//new Resource instance
var user = new User({name: 'John'});
//Prototype methods from Resource class - persist to backend
user.$save().then(function(){
//Delete the user
user.$delete();
});
//Get existing user
var user2 = User.get({id: 2}, function(){
user.name = 'Another name';
user.$save();
});
* $resource it's a wrapper over $http service
Invocation:
* Success is called with (value, responseHeaders) . Error is called with (httpResponse).
** Class actions return empty instance with aditional properties: $promise and $resolved
*** The instance's properties are populated after the $promise is $resolved
Resource instances are instances created by invocation of the constructor with new operator, or by invocation of constructor methods
*Instance actions return promise of the action.
By Alexe Bogdan
Angular $http and $resources
Web Developer, JavaScript Lover, User Experience Professional, working in the web and mobile application development industry.