Pablo Darde
Pablo Darde

Reputation: 6402

How Angular SPA relates to REST API

I'm newbie in node and I'm trying to understand how an Angular SPA, that have some states with uiRouter, can relates to an Express REST API to get data from an database. Can anyone please take me an exemple?

Thanks

Upvotes: 1

Views: 260

Answers (2)

bakkal
bakkal

Reputation: 55448

An AugularJS SPA can talk to REST API through a variety of modules like $resource or a more complete library like Restangular

Example with $resource

For example if your Express API can GET a user on /user/<userId>, and save it back through a POST, you can do this on AngularJS

var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function() {
  user.abc = true;
  user.$save();
});

To understand what $resource will do on HTTP on each action refer to this default mapping

{ 'get':    {method:'GET'},
  'save':   {method:'POST'},
  'query':  {method:'GET', isArray:true},
  'remove': {method:'DELETE'},
  'delete': {method:'DELETE'} };

$http is low level (and built-upon by the REST client libraries)

Another answer here suggested $http. While it's entirely possible to do so, the REST libraries already build upon $http, to give you convenient support for the HTTP verbs and general REST facilities.

If you use $http you'll have to do that manually (not to mention you won't be benefiting from the wisdom and best practices that went into building those libraries)

Upvotes: 1

Denis
Denis

Reputation: 747

I won't recommend to use $resource. It's the object that keeps link to the promise and when promise resolved it'll also contain data itself. So if you want to do some actions when data comes you'll have to assing a callback to that promise anyway. Use $http instead. It's lower level angular abstraction for async requests. And here is the way you can use $http.

Upvotes: 1

Related Questions