Development

AngularJs: $resource vs $http

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("..."):

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

Only implement the methods that you have on your backend.

Return and accept the exact data that you require, typed.

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.