Your SlideShare is downloading. ×
0
Angularjs & REST
Angularjs & REST
Angularjs & REST
Angularjs & REST
Angularjs & REST
Angularjs & REST
Angularjs & REST
Angularjs & REST
Angularjs & REST
Angularjs & REST
Angularjs & REST
Angularjs & REST
Angularjs & REST
Angularjs & REST
Angularjs & REST
Angularjs & REST
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Angularjs & REST

4,586

Published on

Overview on methods to consume RESTful resources with AngularJS.

Overview on methods to consume RESTful resources with AngularJS.

Published in: Technology
0 Comments
7 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
4,586
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
88
Comments
0
Likes
7
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. ANGULARJS & REST Gabriele Mittica www.gabrielemittica.com - @gabrielemittica Corley srl - www.corley.it AngularJsDay 2014
  • 2. What is REST? “Representational State Transfer enables intermediate processing by constraining messages to be self-descriptive: interaction is stateless between requests, standard methods and media types are used to indicate semantics and exchange information, and responses explicitly indicate cacheability.” Roy Fielding, 2000 Client- Server Stateless Cacheable Uniform Interface
  • 3. What is REST? REST helps us to make apps with a frontend layer that works with a separated backend layer that serves RESTful resources Frontend Backend
  • 4. Usually we create applications that drive the logic, manage the data and serve the html to the client. But now we can create an app (for example with AngularJS and HTML5) that works with RESTful resources (JSON or XML)REST
  • 5. AngularJS & REST There are several ways to work with RESTful resources with AngularJS. The most used are: • $http • ngResource • Restangular
  • 6. $http Main features: • It’s a core Angular service • is based on the deferred/promise APIs exposed by the $q service • Useful methods $http.get(), $http.post() … • Auto transforming requests and responses (XSFR, JSON) • Cache support • Interceptors for requests and responses
  • 7. $http example //GET request $http({method: 'GET', url: '/user/123'}). 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. }); //header config $module.run(function($http) { $http.defaults.headers.common.Authentication = 'Basic YmVlcDpib29w' });
  • 8. ngResource Main features: • Uses $resource (facotry that works with $http) to interact with RESTful services • You need to add the script • <script src="//ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular- resource.js"> • And load it into app • angular.module('app', ['ngResource']); • Its methods let to work directly with the RESTful resource
  • 9. ngResource ($resource) example //define the resource var User = $resource('/user/:userId', {userId:'@id'}); //GET and SAVE requests var user = User.get({userId:123}, function() { user.newsletterSubscription = true; user.$save(); //save is a POST request }); //define the resource adding subscribe method var User = $resource('/user/:userId', {userId:'@id'}, {subscribe: {method:'POST', params:{newsletterSubscription:true}}} ); //GET and SAVE requests var user = User.get({userId:123}, function() { user.$subscribe(); });
  • 10. Restangular Main features: • It’s an Angular service to simplify the consume of RESTful API • Lodash (or Underscore) dependency • Get it from https://github.com/mgonto/restangular • Add to your APP: • angular.module('your-app', ['restangular']); • angular.module('your-app').controller('MainCtrl', function($scope, Restangular) { ... }); • You don’t need to remember URLs • It supports nested RestFUL resources and all HTTP methods.
  • 11. Restangular example //define a base path and extractor Restangular.withConfig(function(RestangularConfigurer){ RestangularConfigurer.setBaseUrl("/api/v1/"); RestangularConfigurer.setResponseExtractor(function(response, op) { return response.data; }); }); //define the resource adding subscribe method var baseUsers = Restangular.all('user'); baseUsers.getList().then(function (users) { var firstUser = users[0]; firstUser.name = "Clark Kent"; firstUser.put(); }); { "data": [ { "id": 123, "name": "Superman" }, { "id": 999, "name": "Batman" } ], "status": { "success": true, "time": 201 } }
  • 12. Appendix A: the errors HTTP has a lot of status code (4xx client errors, 5xx server errors) But what if my request is correct, but the result of my request is not correct (for example the users sends a wrong answer in a poll) ? { "data": [], "status": { "success": false, "errorCode": 1001, "errorString": "Wrong answer" } }
  • 13. Appendix B: the authentication HTTP supports authentication (basic, digest…). In our AngularJS app we can add our authentication manager, using the following process: User signed in Server returns a secret key The client uses the key to sign the requests
  • 14. Appendix B: the authentication To do that we can use CryptoJS to sign each request: getSignedParams: function(path, request, myKey, mySecret) { var params = {}; if(request == null) { request = ""; } else { request = JSON.stringify(request); } params.apiKey = myKey; params.signature = CryptoJS.HmacSHA1(path+request, mySecret).toString(); return params; }
  • 15. Appendix B: the authentication There is a problem in this process: If somebody steals my credentials, he can use them for the whole session. A solution is change the credentials in each request (useful in a mobile app but complicated in a web app where the user works on different tabs).
  • 16. CODE GRUSP ON CLOUDCONF.IT THANK YOU http://corsi.corley.it

×