Improve this doc

In this step, you will improve the way our app fetches data.

The last improvement we will make to our app is to define a custom service that represents a RESTful client. Using this client we can make XHR requests for data in an easier way, without having to deal with the lower-level $http API, HTTP methods and URLs.

The most important changes are listed below. You can see the full diff on GitHub:

Template

The custom service is defined in app/js/services.js so we need to include this file in our layout template. Additionally, we also need to load the angular-resource.js file, which contains the ngResource module and in it the $resource service, that we'll soon use:

app/index.html.

  1. ...
  2. <script src="js/services.js"></script>
  3. <script src="lib/angular/angular-resource.js"></script>
  4. ...

Service

app/js/services.js.

  1. var phonecatServices = angular.module('phonecatServices', ['ngResource']);
  2.  
  3. phonecatServices.factory('Phone', ['$resource',
  4. function($resource){
  5. return $resource('phones/:phoneId.json', {}, {
  6. query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
  7. });
  8. }]);

We used the module API to register a custom service using a factory function. We passed in the name of the service - 'Phone' - and the factory function. The factory function is similar to a controller's constructor in that both can declare dependencies via function arguments. The Phone service declared a dependency on the $resource service.

The $resource service makes it easy to create a RESTful client with just a few lines of code. This client can then be used in our application, instead of the lower-level $http service.

app/js/app.js.

  1. ...
  2. angular.module('phonecatApp', ['ngRoute', 'phonecatControllers','phonecatFilters', 'phonecatServices']).
  3. ...

We need to add the 'phonecatServices' module dependency to 'phonecatApp' module's requires array.

Controller

We simplified our sub-controllers (PhoneListCtrl and PhoneDetailCtrl) by factoring out the lower-level $http service, replacing it with a new service called Phone. Angular's $resource service is easier to use than $http for interacting with data sources exposed as RESTful resources. It is also easier now to understand what the code in our controllers is doing.

app/js/controllers.js.

  1. ...
  2.  
  3. phonecatApp.controller('PhoneListCtrl', ['$scope', 'Phone', function($scope, Phone) {
  4. $scope.phones = Phone.query();
  5. $scope.orderProp = 'age';
  6. }]);
  7.  
  8. phonecatApp.controller('PhoneDetailCtrl', ['$scope', '$routeParams', 'Phone', function($scope, $routeParams, Phone) {
  9. $scope.phone = Phone.get({phoneId: $routeParams.phoneId}, function(phone) {
  10. $scope.mainImageUrl = phone.images[0];
  11. });
  12.  
  13. $scope.setImage = function(imageUrl) {
  14. $scope.mainImageUrl = imageUrl;
  15. }
  16. }]);

Notice how in PhoneListCtrl we replaced:

  1. $http.get('phones/phones.json').success(function(data) {
  2. $scope.phones = data;
  3. });

with:

  1. $scope.phones = Phone.query();

This is a simple statement that we want to query for all phones.

An important thing to notice in the code above is that we don't pass any callback functions when invoking methods of our Phone service. Although it looks as if the result were returned synchronously, that is not the case at all. What is returned synchronously is a "future" — an object, which will be filled with data when the XHR response returns. Because of the data-binding in Angular, we can use this future and bind it to our template. Then, when the data arrives, the view will automatically update.

Sometimes, relying on the future object and data-binding alone is not sufficient to do everything we require, so in these cases, we can add a callback to process the server response. The PhoneDetailCtrl controller illustrates this by setting the mainImageUrl in a callback.

Test

We have modified our unit tests to verify that our new service is issuing HTTP requests and processing them as expected. The tests also check that our controllers are interacting with the service correctly.

The $resource service augments the response object with methods for updating and deleting the resource. If we were to use the standard toEqual matcher, our tests would fail because the test values would not match the responses exactly. To solve the problem, we use a newly-defined toEqualData Jasmine matcher. When the toEqualData matcher compares two objects, it takes only object properties into account and ignores methods.

test/unit/controllersSpec.js:

  1. describe('PhoneCat controllers', function() {
  2.  
  3. beforeEach(function(){
  4. this.addMatchers({
  5. toEqualData: function(expected) {
  6. return angular.equals(this.actual, expected);
  7. }
  8. });
  9. });
  10.  
  11.  
  12. beforeEach(module('phonecatServices'));
  13.  
  14.  
  15. describe('PhoneListCtrl', function(){
  16. var scope, ctrl, $httpBackend;
  17.  
  18. beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {
  19. $httpBackend = _$httpBackend_;
  20. $httpBackend.expectGET('phones/phones.json').
  21. respond([{name: 'Nexus S'}, {name: 'Motorola DROID'}]);
  22.  
  23. scope = $rootScope.$new();
  24. ctrl = $controller(PhoneListCtrl, {$scope: scope});
  25. }));
  26.  
  27.  
  28. it('should create "phones" model with 2 phones fetched from xhr', function() {
  29. expect(scope.phones).toEqual([]);
  30. $httpBackend.flush();
  31.  
  32. expect(scope.phones).toEqualData(
  33. [{name: 'Nexus S'}, {name: 'Motorola DROID'}]);
  34. });
  35.  
  36.  
  37. it('should set the default value of orderProp model', function() {
  38. expect(scope.orderProp).toBe('age');
  39. });
  40. });
  41.  
  42.  
  43. describe('PhoneDetailCtrl', function(){
  44. var scope, $httpBackend, ctrl,
  45. xyzPhoneData = function() {
  46. return {
  47. name: 'phone xyz',
  48. images: ['image/url1.png', 'image/url2.png']
  49. }
  50. };
  51.  
  52.  
  53. beforeEach(inject(function(_$httpBackend_, $rootScope, $routeParams, $controller) {
  54. $httpBackend = _$httpBackend_;
  55. $httpBackend.expectGET('phones/xyz.json').respond(xyzPhoneData());
  56.  
  57. $routeParams.phoneId = 'xyz';
  58. scope = $rootScope.$new();
  59. ctrl = $controller(PhoneDetailCtrl, {$scope: scope});
  60. }));
  61.  
  62.  
  63. it('should fetch phone detail', function() {
  64. expect(scope.phone).toEqualData({});
  65. $httpBackend.flush();
  66.  
  67. expect(scope.phone).toEqualData(xyzPhoneData());
  68. });
  69. });
  70. });

You should now see the following output in the Karma tab:

  1. Chrome 22.0: Executed 4 of 4 SUCCESS (0.038 secs / 0.01 secs)

Summary

With the phone image swapper in place, we're ready for step 12 (the last step!) to learn how to improve this application with animations.