AngularJS - $http & $resource Services

39 %
61 %
Information about AngularJS - $http & $resource Services

Published on February 16, 2014

Author: EyalV



AngularJS - $http & $resource Services

Constructor Instance

$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. });

$http.get('/someUrl').success( successCallback ); $'/someUrl', data).success( successCallback );

angular.module('MyApp', []). config(function ($httpProvider) { // Remove the default AngularJS X-Request-With header delete $httpProvider.defaults.headers.common['X-Requested-With']; // Set DO NOT TRACK for all Get requests $httpProvider.defaults.headers.get['DNT'] = '1'; }); $http.get('api/user', { // Set the Authorization header. In an actual app, you would // get the auth token from a service. headers: {'Authorization': 'Basic Qzsda231231'}, params: {id: 5} }).success(function() { // Handle success });

function (d) { return isObject(d) && !isFile(d) ? toJson(d) : d; } function (data) { if (isString(data)) { // strip json vulnerability protection prefix data = data.replace(PROTECTION_PREFIX, ''); if (JSON_START.test(data) && JSON_END.test(data)) data = fromJson(data); } return data; }

// register the interceptor as a service $provide.factory('myHttpInterceptor', function ($q, dependency1, dependency2) { return function (promise) { return promise.then(function (response) { // do something on success return response; }, function (response) { // do something on error if (canRecover(response)) { return responseOrNewPromise } return $q.reject(response); }); } }); $httpProvider.responseInterceptors.push('myHttpInterceptor'); // register the interceptor via an anonymous factory $httpProvider.responseInterceptors.push(function ($q, dependency1, dependency2) { return function (promise) { // same as above } });

$http.get('http://server/myapi', { cache: true }).success(function() { // Handle success });

$http({ method: string, url : string, params: object, data : string or object, headers: object, // or an array of functions. transformRequest: function transform(data, headersGetter), // or an array of functions. transformResponse: function transform(data, headersGetter), cache: boolean //or Cache object, timeout: number, withCredentials: boolean });

$resource( url [, paramDefaults] [, actions] );

Resource Constructor Resource Factory var User = $resource('/user/:userId', { userId: '@id' }); var user = User.get({ userId: 123 }, function () { = true; Resource Instance user.$save(); }); Prototype method Success callback

    action – {string} – The name of action. Method – GET,POST,DELETE & JSONP Params - Optional set of pre-bound parameters for this action. isArray - bool

Constructor Resource Constructor { 'get' : 'save' : 'query' : 'remove': 'delete': {method:'GET' }, {method:'POST'}, {method:'GET', isArray:true}, {method:'DELETE'}, {method:'DELETE'} }; Resource Constructor var User = $resource('/user/:userId'); Resource Factory

User.get ( paramsObj, successFn, errorFn ); User.query ( paramsObj, successFn, errorFn ); // With Data Object (paramsObj, dataObj, successFn, errorFn ); User.remove(paramsObj, dataObj, successFn, errorFn ); User.delete(paramsObj, dataObj, successFn, errorFn );

var promise = $http(httpConfig) .then(function function .then(function function value.$promise = promise; value.$resolved = false; return value; The request details success(response) { }, error(respones) { }) responseInterceptor(response) { }, responseErrorInterceptor(response) { }); Resource Instance

Instance Structure var card = Card.get( function () { = "value"; card.$save(); });

Instance vs. Constructor var User = $resource('/user/:userId', { userId: '@id' }); var user = User.get({ userId: 123); user.$delete(); Users.delete( {} , user); user.$remove() Users.remove( {} , user ) user.$save(); user );

Add a comment

Related presentations

Presentación que realice en el Evento Nacional de Gobierno Abierto, realizado los ...

In this presentation we will describe our experience developing with a highly dyna...

Presentation to the LITA Forum 7th November 2014 Albuquerque, NM

Un recorrido por los cambios que nos generará el wearabletech en el futuro

Um paralelo entre as novidades & mercado em Wearable Computing e Tecnologias Assis...

Microsoft finally joins the smartwatch and fitness tracker game by introducing the...

Related pages

$http - AngularJS

AngularJS is what HTML would have been, ... please check out the $resource service. The $http API is based on the deferred/promise APIs exposed by the $q ...
Read more

Resource - AngularJS

A factory which creates a resource object that lets you interact with RESTful server-side data sources. The returned resource object has action methods ...
Read more

javascript - AngularJS $http and $resource - Stack Overflow

I am newly exposed to AngularJS, so please forgive my ignorance. I have some web services that I want to call. $resource or $http, which one should I use?
Read more

AngularJS – Wikipedia

Das AngularJS-Framework stellt aber bereits zahlreiche Services ... Dazu zählen beispielsweise $http und $resource, ... ist $resource auf REST-Services ...
Read more

Testing $resource services in AngularJS - Stack Overflow

Testing $resource services in AngularJS. ... Extend angularjs $resource service to include common headers. 80. How to handle $resource service errors in ...
Read more

Angular Http - W3Schools

AngularJS $http. The AngularJS $http service makes a request to the server, and returns a response.
Read more

AngularJS.DE → Kapitel 6.11 - Factory, Service und Provider

☰ AngularJS.DE. Artikel; Tutorials; Buch; Jobs; ... Die gesamten Methoden werden in der Dokumentation Services genannt und sind nicht zu verwechseln mit ...
Read more

AngularJS.DE → Startseite

☰ AngularJS.DE. Artikel; Tutorials; Buch; Jobs; Entwickler; Veranstaltungen; Slack 78/634. Login Alles rund um Angular Seit über 3 Jahren. Lernen ...
Read more

Creating a CRUD App in Minutes with Angular's $resource

The $resource service doesn’t come bundled with the main Angular script. You need to download a separate file called angular-resource.js and include it ...
Read more