SlideShare a Scribd company logo
$RESOURCE
VANCOUVER ANGULARJS – APRIL 2ND, 2014
ABOUT @SACHINKAGRAWAL
 I run EDP Software and we build a product called SchedulePro
 Relatively new to AngularJS. Just now starting to use it in
Production scenarios
 Background
8 years as a Program Manager at Microsoft before EDP Software
University of Waterloo alumni
We’re hiring! http://www.edpsoftware.com/about-edp-software/careers/
Email: hr@edpsoftware.com
GOALS FOR TODAY
 Use $resource for connecting to REST web services
 Discuss how to use $resource in a web application
Separate API details from application
Where to put common tasks like data transforms
 Get feedback from the group on what else could be done better!
MY THOUGHTS ON COMMON EXAMPLES
 Most documentation is too simple
 Logic for using $http or $resource is built right into a controller
 Two big issues that I found
REST API changes are not isolated
No common place to handle async status
$RESOURCE INTRO
 Provides a really simple way to grab data from a REST endpoint
Standard methods for query, get, save, delete
Easy to define urls, parameters, custom additions, etc. (see docs)
 Super simple to get started (you should turn this into a factory)
var ResourceObject = $resource("http://foo/Object/…");
var resultData = ResourceObject.query();
//The following call will be bound to the scope and then UI if rendered
//UI will magically update when the request is complete
$scope.foo = ResourceObject.query();
ASYNCHRONOUS CALLS AND PROMISES
 Angular uses promises heavily in many of the built in APIs
 $q is a lightweight promise implementation
 Promises provide the ability to control and chain requests together.
 NOTE: The results of $resource (or $http) are asynchronous. If your
code expects data immediately after calling a query, you will have an
empty result!!!
 NOTE 2: Angular calls the digest loop after $http calls complete
which is why the UI seems to magically get the data
$HTTP VS. $RESOURCE
PROMISES VS. CALLBACKS
 $http uses promises as the design pattern for managing async
actions
 $resource defaults to using a callback structure
Allow you to access the promise exposed by $http
 HELP Me Vangular!?
Suggestions on which route to choose? I exposed the promise from
$resource in my last example.
CALLBACKS FOR SETTING RESULTS
 BAD – What many base examples show
No way of taking action when the async call completes.
Easy to start with but quickly limits your application
 Good – Use the callback function to set variables on the scope
$scope.foo = ResourceObject.query();
ResourceObject.query(function(results){
$scope.foo = results;
//Do any other actions here….
});
ERROR HANDLING – SECOND CALLBACK
 http://stackoverflow.com/questions/20584367/how-to-handle-
resource-service-errors-in-angularjs
Resource.query(function(data) {
// success handler
}, function(error) {
// error handler
});
CREATING A LAYER OF ABSTRACTION
 Isolate - REST APIs may be out of your control (e.g. 3rd party).
Create a factory with your own API
 Simplify/Transform data
Promises can be chained together
The return result from one promise goes into the next as the incoming
data
EXAMPLE
angular.module('sampleApp').factory('resourceAPI', ['$resource', function ($resource) {
var ResourceObject = $resource("http://foo/Object/…");
return {
getTransformedValues: function () {
return ResourceObject.query().$promise.then(function(data) {
//Make whatever transforms are required
//Underscore library is useful here
data = ....
//The returned data will be the result
//when the promise resolves
return data;
});
}, otherFunctionsInAPI: function() {}
};
} ]);
EXAMPLE PART II
Meanwhile.... In your controller
$scope.showSpinner = true;
resourceAPI.getTransformedValues().then(function(data){
$scope.foo = data;
return data;
}, function(error){
//Perform whatever error handling you wish
})[‘finally’](function(){
//Odd finally syntax is for IE8 compat
$scope.showSpinner = false;
});
FUTURE STUFF TO INVESTIGATE/LEARN
 http interceptors
Retry Logic
Security Scenarios
 Response caching

More Related Content

What's hot (14)

PDF
Deep dive into AngularJs for Beginners
Vassilis Pitsounis
 
PDF
Ember.js for Big Profit
CodeCore
 
PPTX
Web apps without internet
MSDEVMTL
 
PDF
Troubleshooting oracle apps
vamsi18here
 
PDF
Andy Bosch - JavaServer Faces in the cloud
Andy Bosch
 
PPTX
Oracle APEX Performance
Scott Wesley
 
PDF
Heroku addons development - Nov 2011
Leonardo Borges
 
PPTX
Integrating Angular.js with Rails (Wicked Good Ruby Conf lightening talk)
Jonathan Linowes
 
PDF
Using Angular with Rails
Jamie Davidson
 
PPT
Web Application FLow
Tokuhiro Matsuno
 
PDF
Introducing Applitude: Simple Module Management
Eric Hamilton
 
PDF
Introduction to Spring Cloud Kubernetes (July 4th, 2019)
Alexandre Roman
 
PDF
Teaming up WordPress API with Backbone.js in Titanium
Jeroen van Dijk
 
PDF
Lessons from helping developers integrate 1,000 APIs with Zapier
Fokke Zandbergen
 
Deep dive into AngularJs for Beginners
Vassilis Pitsounis
 
Ember.js for Big Profit
CodeCore
 
Web apps without internet
MSDEVMTL
 
Troubleshooting oracle apps
vamsi18here
 
Andy Bosch - JavaServer Faces in the cloud
Andy Bosch
 
Oracle APEX Performance
Scott Wesley
 
Heroku addons development - Nov 2011
Leonardo Borges
 
Integrating Angular.js with Rails (Wicked Good Ruby Conf lightening talk)
Jonathan Linowes
 
Using Angular with Rails
Jamie Davidson
 
Web Application FLow
Tokuhiro Matsuno
 
Introducing Applitude: Simple Module Management
Eric Hamilton
 
Introduction to Spring Cloud Kubernetes (July 4th, 2019)
Alexandre Roman
 
Teaming up WordPress API with Backbone.js in Titanium
Jeroen van Dijk
 
Lessons from helping developers integrate 1,000 APIs with Zapier
Fokke Zandbergen
 

Similar to Vancouver AngularJS using $resource in your application (20)

PDF
Cqrs api v2
Brandon Mueller
 
PDF
REST in AngularJS
a_sharif
 
PDF
Drupalcon Mumbai
Sumit Kataria
 
PPTX
JAX-RS. Developing RESTful APIs with Java
Jerry Kurian
 
PDF
Great APIs - Future of Your Progress App
Gabriel Lucaciu
 
PPTX
REST-API introduction for developers
Patrick Savalle
 
PPTX
Angular training - Day 3 - custom directives, $http, $resource, setup with ye...
murtazahaveliwala
 
PDF
Laravel + Restangular Introduction
Andrew Del Prete
 
PDF
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
Evan Mullins
 
PPTX
Day02 a pi.
ABDEL RAHMAN KARIM
 
PDF
Modular Test-driven SPAs with Spring and AngularJS
Gunnar Hillert
 
PPT
Spring, web service, web server, eclipse by a introduction sandesh sharma
Sandesh Sharma
 
PPTX
SharePoint 2013 REST APIs
Giuseppe Marchi
 
PDF
Drupal & AngularJS - DrupalCamp Spain 2014
Juampy NR
 
PDF
Integrate Your Test Automation Tools for More Power
TechWell
 
PDF
Hue: Big Data Web applications for Interactive Hadoop at Big Data Spain 2014
gethue
 
PDF
AngularJS Basic Training
Cornel Stefanache
 
PDF
Resume_AliceZhou
Alice Zhou
 
PPTX
REST Enabling your Oracle Database (2018 Update)
Jeff Smith
 
PDF
Beginning MEAN Stack
Rob Davarnia
 
Cqrs api v2
Brandon Mueller
 
REST in AngularJS
a_sharif
 
Drupalcon Mumbai
Sumit Kataria
 
JAX-RS. Developing RESTful APIs with Java
Jerry Kurian
 
Great APIs - Future of Your Progress App
Gabriel Lucaciu
 
REST-API introduction for developers
Patrick Savalle
 
Angular training - Day 3 - custom directives, $http, $resource, setup with ye...
murtazahaveliwala
 
Laravel + Restangular Introduction
Andrew Del Prete
 
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
Evan Mullins
 
Day02 a pi.
ABDEL RAHMAN KARIM
 
Modular Test-driven SPAs with Spring and AngularJS
Gunnar Hillert
 
Spring, web service, web server, eclipse by a introduction sandesh sharma
Sandesh Sharma
 
SharePoint 2013 REST APIs
Giuseppe Marchi
 
Drupal & AngularJS - DrupalCamp Spain 2014
Juampy NR
 
Integrate Your Test Automation Tools for More Power
TechWell
 
Hue: Big Data Web applications for Interactive Hadoop at Big Data Spain 2014
gethue
 
AngularJS Basic Training
Cornel Stefanache
 
Resume_AliceZhou
Alice Zhou
 
REST Enabling your Oracle Database (2018 Update)
Jeff Smith
 
Beginning MEAN Stack
Rob Davarnia
 
Ad

Recently uploaded (20)

PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PDF
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PPTX
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Tally software_Introduction_Presentation
AditiBansal54083
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Ad

Vancouver AngularJS using $resource in your application

  • 2. ABOUT @SACHINKAGRAWAL  I run EDP Software and we build a product called SchedulePro  Relatively new to AngularJS. Just now starting to use it in Production scenarios  Background 8 years as a Program Manager at Microsoft before EDP Software University of Waterloo alumni We’re hiring! http://www.edpsoftware.com/about-edp-software/careers/ Email: [email protected]
  • 3. GOALS FOR TODAY  Use $resource for connecting to REST web services  Discuss how to use $resource in a web application Separate API details from application Where to put common tasks like data transforms  Get feedback from the group on what else could be done better!
  • 4. MY THOUGHTS ON COMMON EXAMPLES  Most documentation is too simple  Logic for using $http or $resource is built right into a controller  Two big issues that I found REST API changes are not isolated No common place to handle async status
  • 5. $RESOURCE INTRO  Provides a really simple way to grab data from a REST endpoint Standard methods for query, get, save, delete Easy to define urls, parameters, custom additions, etc. (see docs)  Super simple to get started (you should turn this into a factory) var ResourceObject = $resource("http://foo/Object/…"); var resultData = ResourceObject.query(); //The following call will be bound to the scope and then UI if rendered //UI will magically update when the request is complete $scope.foo = ResourceObject.query();
  • 6. ASYNCHRONOUS CALLS AND PROMISES  Angular uses promises heavily in many of the built in APIs  $q is a lightweight promise implementation  Promises provide the ability to control and chain requests together.  NOTE: The results of $resource (or $http) are asynchronous. If your code expects data immediately after calling a query, you will have an empty result!!!  NOTE 2: Angular calls the digest loop after $http calls complete which is why the UI seems to magically get the data
  • 7. $HTTP VS. $RESOURCE PROMISES VS. CALLBACKS  $http uses promises as the design pattern for managing async actions  $resource defaults to using a callback structure Allow you to access the promise exposed by $http  HELP Me Vangular!? Suggestions on which route to choose? I exposed the promise from $resource in my last example.
  • 8. CALLBACKS FOR SETTING RESULTS  BAD – What many base examples show No way of taking action when the async call completes. Easy to start with but quickly limits your application  Good – Use the callback function to set variables on the scope $scope.foo = ResourceObject.query(); ResourceObject.query(function(results){ $scope.foo = results; //Do any other actions here…. });
  • 9. ERROR HANDLING – SECOND CALLBACK  http://stackoverflow.com/questions/20584367/how-to-handle- resource-service-errors-in-angularjs Resource.query(function(data) { // success handler }, function(error) { // error handler });
  • 10. CREATING A LAYER OF ABSTRACTION  Isolate - REST APIs may be out of your control (e.g. 3rd party). Create a factory with your own API  Simplify/Transform data Promises can be chained together The return result from one promise goes into the next as the incoming data
  • 11. EXAMPLE angular.module('sampleApp').factory('resourceAPI', ['$resource', function ($resource) { var ResourceObject = $resource("http://foo/Object/…"); return { getTransformedValues: function () { return ResourceObject.query().$promise.then(function(data) { //Make whatever transforms are required //Underscore library is useful here data = .... //The returned data will be the result //when the promise resolves return data; }); }, otherFunctionsInAPI: function() {} }; } ]);
  • 12. EXAMPLE PART II Meanwhile.... In your controller $scope.showSpinner = true; resourceAPI.getTransformedValues().then(function(data){ $scope.foo = data; return data; }, function(error){ //Perform whatever error handling you wish })[‘finally’](function(){ //Odd finally syntax is for IE8 compat $scope.showSpinner = false; });
  • 13. FUTURE STUFF TO INVESTIGATE/LEARN  http interceptors Retry Logic Security Scenarios  Response caching