Restangular (https://github.com/mgonto/restangular) is a very nice replacement for Agular’s http://docs.angularjs.org/api/ng.$http service. It has a fairly straightforward usage, documentation is OK, and I believe, it is a common choice among Angular developers.
Let’s say we have an Angular controller, and we want to expose a web resource to our $scope. Code can look something like that:
If you want to simplify things, you can use the fact that Restangular returns a promise, and Angular can handle promises transparently. This can shorten your code to that:
While this is all fine and dandy, it is possible that in some cases, we would like to make things more object-oriented. Restangular allows us to enhance obtaining resources: https://github.com/mgonto/restangular#creating-new-restangular-methods. However, while Restangular proclaims itself as a service, in a traditional MVC sense, it is just a http://en.wikipedia.org/wiki/Data_access_object with enhanced capabilities. So, a purist like me would feel uncomfortable using that hybrid dao/service approach. Wouldn’t it be slightly better to define a service that handles obtaining someVariable objects? This service itself can depend on Restangular for actually making the rest call. So the below code:
Can be rewritten into:
The additional benefit now that we have is you have a named function for getting the someOtherVariable, and you can use it in other controllers/services without having to repeat code. Also, the unit test for the controller becomes very easy in the second case.
A sample implementation of the service can be:
But what if we want to make a Restangular call in our service and ‘ehnance’ it additionally. Suppose a Restangular call returns :
And we would like our service to return:
If you wanted to achieve that directly in a controller, you would do something like that:
However, if you were using a service, you would expect to have something like that:
This, while it appears trivial, is slightly more tricky due to nature of promises. A sample implementation can be:
And since this is also a bit hard to test, below is a sample jasmine unit test:
And the TestUtils’ method:
It is worth to note that Angular devs are deprecating the automatic resolve of promises:
So your code would look a bit more cluttered but confusion would be avoided.
This plunkr shows that in angular 1.2rc3 the first method works:
But if you were to try to take advantage of the automatic unrwapping of promises (which is deprecated in rc3, you are out of luck):