AngularJs: $resource vs $http

with 3 Comments

A few months back we started using TypeScript in our current project (yay, great productivity boost and bug-catcher!). We used $resource for our HTTP-requests and found ourselfs in a pickle when it came to defining them in TypeScript. This was roughly how a controller and $resouce-service looked like:

But the typings for $resource("api/user") can not be inferred this way, and even if it could its to generic to be reliable. DefinitelyTyped/angularjs tells us this spec for the return of $resource("..."):

A resource class looks like this:

Our first attempt was to not export userServiceFactory and instead create a interface, extending IResourceClass that looks like our WebAPI-controller:

But what if:

  1. Not all methods are implemented. In our example above we do not have a DELETE but it looks like we have in TypeScript.
  2. Not all methods returns the same type. POST/PUT/GET/DELETE might return different data, one generic type just isnt enough!
  3. We want to define an extra method (pushing the limits of what might be alright for a REST-purist) like this:

Creating manual interfaces reflecting your $resource is a pain, so we started looking for alternatives…

$http to the rescue!

Transforming the above userService to use $http was simple and so was the result:

this will provide you with a simple and typed service for interacting with your controllers. Our 3 if’s are solved:

  1. Only implement the methods that you have on your backend.
  2. Return and accept the exact data that you require, typed.
  3. Simply extend your url for methods like our “setDistance”-method.

Another great advantage of using this approach is that there is alot less magic. This way you get a understanding over the requests you are creating and get full control all the way.

So this is fantastic, right? we have a tool for calling our backend that will give us typed parameters and results. But how about those parameters and results, who does the manual typing, making sure all parameters and all the result’s properties are accounted for? The solution is called TypeWriter and here is an earlier post about that: TypeScript codegeneration with Typewriter.


Edit: And here is a later blogpost, when you are ready to take this to the next level: Angular & TypeScript: Typed interaction with your WebAPI-backend

3 Responses

  1. […] written previously about angulars $http/$resource and about typescript codegeneration, now its time to write a few words about my current project […]

  2. […] written previously about angulars $http/$resource and about typescript codegeneration, now its time to write a few words about my current project […]

  3. Aluan
    | Reply

    I definitely agree. $resource does not map well to TypeScript and $http is simpler. More importantly, whether you are using TypeScript or not, $http is far more composable. Nice post.

Leave a Reply