Forward Advance Learning

Services and Factories as AJAX wrappers

Services are often used as API accessors to take API code out of a controller and keep the controller focused on $scope.

Here is a service that can talk to Github:

angular.module('app', [])
.service('github', function( $http ) {
var url = 'https://api.github.com/events?callback=JSON_CALLBACK';
this.getEvents = function () {
return $http.jsonp(url);
}
});

Further Reading

For more on the technical and conceptual differences between services and factories, read my Stack Overflow post here:

http://stackoverflow.com/a/27545899/687677

Flickr Service

We are going to refactor our Flickr exercise to use a service. If you didn't complete the Flickr exercise, you can download some sample code from here (look in the exercise section)

  1. Create a Flickr service, that encapsulates the AJAX logic needed to pull data from the Flickr API. Return the $http object so that we can apply callbacks. You can use the code above as a template.
  2. Return to your Flickr exercise. Inject the Flickr service into your controller and use this instead.