rest in angularjs

34
The Rest Side Of Things in AngularJS A. Sharif @sharifsbeat

Upload: asharif

Post on 16-Jul-2015

897 views

Category:

Software


0 download

TRANSCRIPT

The Rest Side Of Things in AngularJS

A. Sharif

@sharifsbeat

Basic interactions with a restful API is easy with AngularJS...

$http

$http

$http Service is a core Angular Service

Based on $q (deferred/promise APIs)

GET, POST, PUT and DELETE methods

Simple to use

$http

var cb = function(data, status, headers, config) {// do something

};

$http.get(‘users/2’).success(cb); //.error(errorCb);

$http

Alternative

var httpConfig = {method: ‘POST’,url : ‘users’,data : {name : ‘foo’},// headers : override header

}

$http(httpConfig).success(successCb); //.error(errorCb);

$http

More features...

Interceptors, transformations, caching

Foundation for building your own Rest Resource implementation

https://docs.angularjs.org/api/ng/service/$http

$resource

$resource

Install via bower/npm

angular.module(‘app’, [‘ngResource’]);

Based on $http

$resource

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

$resourcePredefined Set Of Actions

{'get': {method:'GET'},

'save': {method:'POST'},

'query': {method:'GET', isArray:true},

'remove': {method:'DELETE'},

'delete': {method:'DELETE'} };

$resource

Adding own Methods is simple

var Users = $resource('/api/users/:id', {id:'@id'}, {! update : {! ! method : 'PUT'! }});

// /api/users/1 PUT

Users.update({ id: 1, name: ‘foo’ });

$resourcevar Users = $resource('/api/users/:id', {id:'@id'}, {! update : {! ! method : 'PUT'! }});

var users = Users.query(function() {! var userA = users[0];! userA.name = 'foobar';! userA.$update(function(result) {! ! console.log('has been saved', result);! });});

$resource

Access the $http promise via the $promise property

Users.get({id : 1}).$promise.then(function(user) {! // success}, function(error) {! // error});

$resource

$resolved property is set to false until server interaction is completed.

$resource

function createResource(name, apiName) {! Module.provider(name + 'Resource', function() {! ! this.$get = ['$resource', function($resource) {! ! ! var Resource = $resource('http://rest.local/api/'+ apiName +'/:id', {id:'@id'}, {! ! ! ! update: {! ! ! ! ! method: 'PUT'! ! ! ! }! ! ! });

! ! ! return Resource;! ! }];! });}

createResource('User', 'users');

$resource

Very easy to use

Methods to quickly interact with a REST api without having to deal with the low level $http.

Restangular

Restangular

Supports all HTTP Methods

Nested RESTful Resources

Promises

Extendable

Requires lodash

Restangular

Install via bower/npm

angular.module(‘app’, [‘restangular’]);

Restangular

Access inside a controllerangular.module(‘app’).controller($scope, Restangular) {

// do something here...});

Restangular

Define a main route or object

Restangular.all(‘users’);

Restangular.one(‘users’, 2);

RestangularConfiguration

Via config

app.config(function(RestangularProvider) { RestangularProvider.setBaseUrl('/api/'); });

Via run

app.run(function(Restangular) { Restangular.setBaseUrl(‘/api/‘);});

Restangular

Override global configuration

app.factory(‘otherRestanagular’, function(Restangular) {

return Restangular.withConfig(function(RestangularConfigurer) {

RestangularConfigurer.setBaseUrl('http://somethingelse');

});

});

Restangular

URL Building

// This will do ONE get to /users/1/tasks/12/substasks

Restangular.one("users",1).one("tasks", 12).all("subtasks");.getList()

// This will do ONE get to /users/1/tasks/12/subtasks/234

Restangular.one("users", 1).one("tasks", 12).one("subtasks", 234).get()

// POST /users/1/tasks/12/subtasks

Restangular.one("users", 1).one("tasks", 12).all("subtasks").post({name: "Foo"});

// DELETE /users/1/tasks/12

Restangular.one("users", 1).one("tasks", 12).remove();

Restangular

HTTP Methodsvar user = Restangular.one(‘users’, 1);user.get(); // GET /users/1user.getList('tasks'); // GET /users/1/tasksuser.put(); // PUT /users/1user.post(); // POST /users/1user.remove(); // DELETE /users/1user.head(); // HEAD /users/1user.trace(); // TRACE /users/1user.options(); // OPTIONS /users/1user.patch(); // PATCH /users/1

Restangular

Custom Methods

Restangular.extendCollection('users', function(users) { users.getTotal = function() { // do something here... };

return users; });

var users = Restangular.all('users').getList();

users.then(function(accounts) { users.getTotal(); // invoke the custom collection method});

Restangular

Error HandlingUser.get().then(function(success) {

// success }, function(error) {

// do something});

Restangular

Setting Default HeadersRestangularProvider.setDefaultHeaders({token: "foo"});

Restangular

Decoupling a Restangular Serviceapp.factory('Users', function(Restangular) {! return Restangular.service('users');});

app.controller(‘testController’, function(Users) {// Users.getList();

});

RestangularRequest / Response / Error Interceptors

Restangular.addRequestInterceptor(function(element, method, route, url) {

! if (method == 'put') {! ! delete element.valueNotToBeSent;! }

! return elem;});

Restangular

Element Transformations

Collection and Model Custom Methods

Self Reference in Resources

Restangular

Large set of Methods for elements and Collections

Extendable with Custom Operations

Configuarable

https://github.com/mgonto/restangular

Thank You.

@sharifsbeat