Sunday, February 1, 2015

Using Angular $resource against Web API 2 backend

This week I tried answering a question on StackOverflow about using Angular's $resource against a .NET WebAPI v2 backend:



To me it seemed like the poster of this question was not using WebAPI in a RESTful way which caused the trouble with WebAPI. I've seen this before where colleagues are using one WebAPI controller to server different types of objects and then need to do custom routing and what not in order to make it work.
My recommendation would be to not do that. Have 1 controller for 1 type of object and map the HTTP verbs on it.

Having said that, I wanted play around with $resource and did that in a proof-of-concept application that I put on GitHub: https://github.com/jochenvanwylick/SODemoAngularResourceWebAPI

I'm using LightInject for dependency injection ( since that was on my list to try ) and OWIN selfhost to host the WebAPI v2 backend.

Here's the Angular application that uses the ngResource module:


I added the listAll method in order to talk to the Get() method in the backend. You need to specify that the result is an array as opposed to an object. Once you get an item from resource, you can just save it with $save().

Here's the C# controller that handles all the methods that are being called by AngularJS.

So yeah, it's nice - $resource. I've used an injecteable service thusfar, but will consider using $resource in the future.

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
    or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

    ReplyDelete