SlideShare uma empresa Scribd logo
1 de 25
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 );
$http.post('/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 () {
user.abc = 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
User.save

(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 () { card.name = "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();

Users.save( user );
eyalvardi.wordpress.com

Mais conteúdo relacionado

Mais procurados

Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax plugins
Inbal Geffen
 
Sprout core and performance
Sprout core and performanceSprout core and performance
Sprout core and performance
Yehuda Katz
 
jQuery: out with the old, in with the new
jQuery: out with the old, in with the newjQuery: out with the old, in with the new
jQuery: out with the old, in with the new
Remy Sharp
 

Mais procurados (20)

Javascript - Beyond-jQuery
Javascript - Beyond-jQueryJavascript - Beyond-jQuery
Javascript - Beyond-jQuery
 
Angular Promises and Advanced Routing
Angular Promises and Advanced RoutingAngular Promises and Advanced Routing
Angular Promises and Advanced Routing
 
Angular 2 Architecture
Angular 2 ArchitectureAngular 2 Architecture
Angular 2 Architecture
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
 
Angular js routing options
Angular js routing optionsAngular js routing options
Angular js routing options
 
Dart and AngularDart
Dart and AngularDartDart and AngularDart
Dart and AngularDart
 
Upgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.xUpgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.x
 
AngulrJS Overview
AngulrJS OverviewAngulrJS Overview
AngulrJS Overview
 
Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax plugins
 
Hack tutorial
Hack tutorialHack tutorial
Hack tutorial
 
Modules and injector
Modules and injectorModules and injector
Modules and injector
 
Sprout core and performance
Sprout core and performanceSprout core and performance
Sprout core and performance
 
Owl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOwl: The New Odoo UI Framework
Owl: The New Odoo UI Framework
 
Angular 2.0 Views
Angular 2.0 ViewsAngular 2.0 Views
Angular 2.0 Views
 
jQuery: out with the old, in with the new
jQuery: out with the old, in with the newjQuery: out with the old, in with the new
jQuery: out with the old, in with the new
 
Nodejs do teste de unidade ao de integração
Nodejs  do teste de unidade ao de integraçãoNodejs  do teste de unidade ao de integração
Nodejs do teste de unidade ao de integração
 
Routing And Navigation
Routing And NavigationRouting And Navigation
Routing And Navigation
 
정오의 데이트 for iOS 코드 정리
정오의 데이트 for iOS 코드 정리정오의 데이트 for iOS 코드 정리
정오의 데이트 for iOS 코드 정리
 
Flask and Angular: An approach to build robust platforms
Flask and Angular:  An approach to build robust platformsFlask and Angular:  An approach to build robust platforms
Flask and Angular: An approach to build robust platforms
 

Destaque

Destaque (13)

Vancouver AngularJS using $resource in your application
Vancouver AngularJS using $resource in your application Vancouver AngularJS using $resource in your application
Vancouver AngularJS using $resource in your application
 
AngularJS Animations
AngularJS AnimationsAngularJS Animations
AngularJS Animations
 
AngularJS Testing
AngularJS TestingAngularJS Testing
AngularJS Testing
 
Forms in AngularJS
Forms in AngularJSForms in AngularJS
Forms in AngularJS
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
 
Async & Parallel in JavaScript
Async & Parallel in JavaScriptAsync & Parallel in JavaScript
Async & Parallel in JavaScript
 
OOP in JavaScript
OOP in JavaScriptOOP in JavaScript
OOP in JavaScript
 
Rachel's grandmother's recipes
Rachel's grandmother's recipesRachel's grandmother's recipes
Rachel's grandmother's recipes
 
AngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedAngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get started
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 
29 Essential AngularJS Interview Questions
29 Essential AngularJS Interview Questions29 Essential AngularJS Interview Questions
29 Essential AngularJS Interview Questions
 
Angularjs - lazy loading techniques
Angularjs - lazy loading techniques Angularjs - lazy loading techniques
Angularjs - lazy loading techniques
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your Niche
 

Semelhante a AngularJS - $http & $resource Services

Aura Project for PHP
Aura Project for PHPAura Project for PHP
Aura Project for PHP
Hari K T
 
Building Smart Async Functions For Mobile
Building Smart Async Functions For MobileBuilding Smart Async Functions For Mobile
Building Smart Async Functions For Mobile
Glan Thomas
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
Michael Peacock
 

Semelhante a AngularJS - $http & $resource Services (20)

Angular server-side communication
Angular server-side communicationAngular server-side communication
Angular server-side communication
 
Aura Project for PHP
Aura Project for PHPAura Project for PHP
Aura Project for PHP
 
Lazy evaluation drupal camp moscow 2014
Lazy evaluation drupal camp moscow 2014Lazy evaluation drupal camp moscow 2014
Lazy evaluation drupal camp moscow 2014
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & REST
 
What's new in jQuery 1.5
What's new in jQuery 1.5What's new in jQuery 1.5
What's new in jQuery 1.5
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
Angular Tutorial Freshers and Experienced
Angular Tutorial Freshers and ExperiencedAngular Tutorial Freshers and Experienced
Angular Tutorial Freshers and Experienced
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
 
Spring data iii
Spring data iiiSpring data iii
Spring data iii
 
Bacbkone js
Bacbkone jsBacbkone js
Bacbkone js
 
Intro to advanced caching in WordPress
Intro to advanced caching in WordPressIntro to advanced caching in WordPress
Intro to advanced caching in WordPress
 
Building Smart Async Functions For Mobile
Building Smart Async Functions For MobileBuilding Smart Async Functions For Mobile
Building Smart Async Functions For Mobile
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
Developing cacheable backend applications - Appdevcon 2019
Developing cacheable backend applications - Appdevcon 2019Developing cacheable backend applications - Appdevcon 2019
Developing cacheable backend applications - Appdevcon 2019
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 
Nashvile Symfony Routes Presentation
Nashvile Symfony Routes PresentationNashvile Symfony Routes Presentation
Nashvile Symfony Routes Presentation
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2
 
Mashing up JavaScript
Mashing up JavaScriptMashing up JavaScript
Mashing up JavaScript
 
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsMashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web Apps
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
 

Mais de Eyal Vardi

Mais de Eyal Vardi (20)

Why magic
Why magicWhy magic
Why magic
 
Smart Contract
Smart ContractSmart Contract
Smart Contract
 
Performance Optimization In Angular 2
Performance Optimization In Angular 2Performance Optimization In Angular 2
Performance Optimization In Angular 2
 
Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)
 
Angular 2 NgModule
Angular 2 NgModuleAngular 2 NgModule
Angular 2 NgModule
 
Angular 2 - Ahead of-time Compilation
Angular 2 - Ahead of-time CompilationAngular 2 - Ahead of-time Compilation
Angular 2 - Ahead of-time Compilation
 
Http Communication in Angular 2.0
Http Communication in Angular 2.0Http Communication in Angular 2.0
Http Communication in Angular 2.0
 
Angular 2.0 Dependency injection
Angular 2.0 Dependency injectionAngular 2.0 Dependency injection
Angular 2.0 Dependency injection
 
Angular 2.0 Routing and Navigation
Angular 2.0 Routing and NavigationAngular 2.0 Routing and Navigation
Angular 2.0 Routing and Navigation
 
Async & Parallel in JavaScript
Async & Parallel in JavaScriptAsync & Parallel in JavaScript
Async & Parallel in JavaScript
 
Angular 2.0 Pipes
Angular 2.0 PipesAngular 2.0 Pipes
Angular 2.0 Pipes
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 
Modules in ECMAScript 6.0
Modules in ECMAScript 6.0Modules in ECMAScript 6.0
Modules in ECMAScript 6.0
 
Proxies in ECMAScript 6.0
Proxies in ECMAScript 6.0Proxies in ECMAScript 6.0
Proxies in ECMAScript 6.0
 
Iterators & Generators in ECMAScript 6.0
Iterators & Generators in ECMAScript 6.0Iterators & Generators in ECMAScript 6.0
Iterators & Generators in ECMAScript 6.0
 
Symbols in ECMAScript 6.0
Symbols in ECMAScript 6.0Symbols in ECMAScript 6.0
Symbols in ECMAScript 6.0
 
Objects & Classes in ECMAScript 6.0
Objects & Classes in ECMAScript 6.0Objects & Classes in ECMAScript 6.0
Objects & Classes in ECMAScript 6.0
 
Scope & Functions in ECMAScript 6.0
Scope & Functions in ECMAScript 6.0Scope & Functions in ECMAScript 6.0
Scope & Functions in ECMAScript 6.0
 
AngularJS Internal
AngularJS InternalAngularJS Internal
AngularJS Internal
 
Node.js Spplication Scaling
Node.js Spplication ScalingNode.js Spplication Scaling
Node.js Spplication Scaling
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 

AngularJS - $http & $resource Services

  • 1.
  • 3.
  • 4.
  • 5. $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. });
  • 7.
  • 8. 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 });
  • 9. 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; }
  • 10. // 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 } });
  • 12. $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 });
  • 13.
  • 14.
  • 15.
  • 16. $resource( url [, paramDefaults] [, actions] );
  • 17. Resource Constructor Resource Factory var User = $resource('/user/:userId', { userId: '@id' }); var user = User.get({ userId: 123 }, function () { user.abc = true; Resource Instance user.$save(); }); Prototype method Success callback
  • 18.     action – {string} – The name of action. Method – GET,POST,DELETE & JSONP Params - Optional set of pre-bound parameters for this action. isArray - bool
  • 19. 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
  • 20. User.get ( paramsObj, successFn, errorFn ); User.query ( paramsObj, successFn, errorFn ); // With Data Object User.save (paramsObj, dataObj, successFn, errorFn ); User.remove(paramsObj, dataObj, successFn, errorFn ); User.delete(paramsObj, dataObj, successFn, errorFn );
  • 21. 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
  • 22. Instance Structure var card = Card.get( function () { card.name = "value"; card.$save(); });
  • 23. 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(); Users.save( user );
  • 24.