Angular Services

The Built In Ones

What Are Services

  • Services are modules in Angular
     
  • They can be injected into other modules, such as Controllers
     
  • Like NPM modules, we use these to share code and data across multiple applications or multiple controllers

For Example: $http

angular.module('app',[])
  .controller("MainController", function($scope, $http){

    $scope.performSearch = function(searchQuery) {
      
      var searchUrl = 
            "https://api.spotify.com/v1/search?type=artist&q=sound providers";

      var spotifyQueryRequest = $http({
          method: "GET",
          url: searchUrl
      });
      
      // $http requests return promises
      spotifyQueryRequest.then(function(data){
        console.log(data)
      }); 
    }
  }

Angular's service for performing AJAX

For Example: $http

var get = $http({
            method: "GET",
            url: postUrl,
            params: queryParamsJson,
            headers: headersJson
          });

var post = $http({
             method: "POST",
             url: postUrl,
             data: someJsonObject,
             headers: headersJson
          });
      

HTTP requests are highly configurable, here are the most common options

For Example: $location

angular.module('app',[])
  .controller("MainController", function($scope, $location){
      $location.url('this/is/a/?fancy=url');

      console.log($location.url());
      console.log($location.path());
      console.log($location.search());
    }
  }

/*
/this/is/a/?fancy=url
/this/is/a/
Object { fancy: "url" }

and the URL becomes: http://localhost:8000/#/this/is/a/?fancy=url
*/

$location is based on window.location, this is used to get and set the URL.

For Example: $window

angular.module('app',[])
  .controller("MainController", function($scope, $window, $location){
      $location.url('this/is/a/?fancy=url');

      $window.setInterval(function(){
        console.log($location.url());
        console.log($location.path());
        console.log($location.search());
      }, 1000);
      
    }
  }

When you need something that normally lives on window (like setTimeout and setInterval) the best practice is to  use $window instead of window directly.

For Example: $exceptionHandler

angular.module('exceptionOverride', [])
  .factory('$exceptionHandler', function() {
    return function(exception, cause) {
      exception.message += ' (caused by "' + cause + '")';
      throw exception;
    };
});

By default, Angular simply logs exceptions to the console and tries its best to keep running. This service can be used to overwrite that behavior.

In this case, we "fail harder" and actually crash the application

But Wait, Theres MORE!

https://docs.angularjs.org/api/ng/service

Reading through the list, you may find something you wished was baked into Angular, that really IS baked in!

Questions?

Made with Slides.com