Skip to content

Instantly share code, notes, and snippets.

@k26dr
Last active August 11, 2016 20:38
Show Gist options
  • Save k26dr/6f1a76f85c5fb668e20f to your computer and use it in GitHub Desktop.
Save k26dr/6f1a76f85c5fb668e20f to your computer and use it in GitHub Desktop.
Angular Services

Angular Services


Learning Objectives

SWBAT:

  • Use Angualar's built in services in controllers
  • Create a custom service using the .factory method
  • Use custom services in Angular controllers

What are services?

  • Blocks of code that can be shared between controllers
  • Angular has a bunch of built in services that provide commonly used functionality like AJAX ($http).

The 2 types of services

  1. Angular built-in service. Start with a $ sign ($http, $cookieStore, $interval, etc.)
  2. Custom service. Written by us. To do whatever we'd like.

Why do we need Angular services?

Because we're too lazy to provide the functionality on our own.


Why do we need custom services?

  • To share repeating functionality across controllers, keep code DRY
  • Example: Service that wraps your REST backend.

Preview: Why do we need multiple controllers?

Our controllers will eventually be tied to routes. Each route, will have one controller, so when we navigate to a new route, the old controller and all of its data get destroyed.


Review: Creating an Angular application

  • Create an Angular application called ServicePractice
    • Feel free to copy in yesterday's code as a starting point, but make the necessary modifications
  • Create a controller, AjaxController with the variables:
    • this.query, an empty string
    • this.search, a blank function
    • this.result, an empty string
  • Inside the controller create a text input, a "Search" button, and a result div
  • Bind this.query to the text input using ng-model
  • Bind this.search to the button using ng-click
  • Bind this.result to the result div using {{ }}

Using built-in services

  1. Inject your service into the controller
  2. Add the service to the controller's argument list
  3. Invoke the service in your controller

angular.module("ServicePractice")
	.controller("AjaxController", AjaxController)

// 1. Inject service into controller
AjaxController.$inject = ['$http']

// 2. Add service to controller's argument list
function AjaxController ($http) {
    var vm = this
    vm.query = ""
    vm.result = {}
	vm.search = function () {
		 // 3. Invoke service
        $http.get("http://jsonplaceholder.typicode.com/posts/" 
        + vm.query).then(function (response) {
            vm.result = response.data
        })
    }
}

Google Time!


Independent Practice

  • Create a new controller CountdownController
  • Make sure to include the file and proper markup in the HTML
  • Use the $interval service to create a countdown timer that counts down the number of days, hours, minutes, and seconds until the end of the course (May 27 @ 5pm)

Custom services

  • For now, we will stick custom services in the js/services directory
  • Later on, we will be covering how to group files by feature instead of type (eg. authentication/ instead of controllers/)
  • NOTE: Services can use other services, but we will cover that later

Custom services

// js/services/MathService.js

angular.module("ServicePractice")
    .factory("MathService", MathService)

function MathService () {
    var service = {}
    service.square = function (n) {
        return n*n
    }
	return service
}

Custom Services

// js/controllers/AjaxController.js

angular.module("ServicePractice")
	.controller("AjaxController", AjaxController)

AjaxController.$inject = ['$http', 'MathService']

function AjaxController ($http, MathService) {
    var vm = this
    vm.query = ""
    vm.result = {}
	vm.search = function () {
        $http.get("http://jsonplaceholder.typicode.com/posts/" 
        + MathService.square(vm.query)).then(function (response) {
            vm.result = response.data
        })
    }
}

Independent Practice

  • Add a function cubeModX to MathService that:
    • takes two arguments, n and x
    • returns (cube of n) modulus x
  • Modify the query function to use cubeModX instead of square

Independent Practice

  • Create a service OpenWeather
  • Add a function getWeather to the service that:
    • Takes a parameter cityId and returns the current temperature of that city (units will be Celcius)
  • Inject the service into AjaxController
  • Use the input box, search button, and result div to search for and display the entered city id's current temperature

Independent Practice (cont.)


Interview Practice

  1. Write a function that returns a boolean indicating whether or not a string is a palindrome.
  2. Write a function that returns a boolean indicating whether an array contains any duplicate values.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment