AngularJS AJAX calls

AngularJS is a JavaScript framework that allows us to create Single Page Applications (SPA). If we use AngularJS we can bind from our HTML views to JavaScript files (controllers). Controllers will offer the data to the view. Typically this data is retrieved from REST services using Ajax calls.

The goal of this post is to show how to make AJAX calls using AngularJS. I will illustrate two different ways to do it, the first one helps to understand how the asynchronous call works, the second one is an easier way to do it using a higher-level service.

Using $http and $q

One way to make AJAX calls using AngularJS is using the services $http and $q:

  • The $http service allows us to make the GET and POST calls.
  • The $q service is used to wait asynchronously for the response, basically it is a deferred result, it returns a “promise” that will response after some time. After some time the deferred can be “resolved” or “rejected”.   The method using this deferred can add two call-backs to it one to execute when it is resolved and one when it is rejected.

Let say we have a controller that needs to populate some data asynchronously. I like to dedicate the controller to define the binds for our views. The AJAX call will be executed in a different file, a repository.

AngularJS – Controller: The module will call a repository and add set the response in the scope when the deferred is resolved.

angular js controller

AngularJS – Repository: The repository make an AJAX Get request to a ASP.NET WebAPI Controller.

angular js repository

We can write the same repository with less lines using shortcut methods:

angular js repository

This solution works but there is an easier way to do AJAX calls…

Using $resource

This service lets us interact with RESTful server-side data sources with a higher-level than the $http service. The $resource service is defined in the module ‘ngResource’ and this module is in the file angular-resource.js.

The first thing that we need to do is to reference the angular-resource.js file and add this module as a dependency of our module:

ngResource reference

ngResource reference

Using the $resource we can write our controller and repository easier because we don’t have to deal directly with deferred objects.

This is now the implementation of our controller and repository using the Angular service $resource , really easy!

angular js repository and controller

Your feedback is important...

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.