SEI-Example
  • Introduction
  • About These Notes
  • Syllabus
  • Development Workflow
    • Installfest
      • Mac OSX
      • Linux
      • Git Configuration
      • Sublime Packages
    • Command Line
      • The Terminal
      • Filesystem Navigation
      • File Manipulation
      • Additional Topics
    • Intro to Git
      • Version Control
      • Local Git
      • Remote Git
      • Git Recipes
    • Group Collaboration
      • Git Workflows
      • Project Roles and Tools
    • VS Code Tips & Tricks
  • HTML/CSS
    • HTML
    • CSS Selectors
    • CSS Box Model and Positioning
      • Box Model
      • Display and Positioning
      • Flexbox
      • Grid
      • Flexbox & Grid Games
      • Floats and Clears
      • Additional Topics
    • Advanced CSS
      • Responsive Design
      • Pseudo-Classes/Elements
      • Vendor Prefixes
      • Custom Properties
      • Additional Topics
    • Bootstrap
    • CSS Frameworks
    • Accessibility
  • JavaScript
    • Primitives
    • Arrays
    • Objects
    • Control Flow
      • Boolean Expressions
      • Conditionals
      • Loops
      • Promises
    • Functions
      • Callbacks
      • Timing Functions
      • Iterators
    • DOM and Events
    • DOM Manipulation
    • HTML5 Canvas
    • How To Reduce Redundancy
    • (2019) JavaScript OOP
    • (2016) OOP with Classes
    • (1995) OOP with Prototypes
      • Constructors
      • Prototypes
    • Intro to TDD
    • Scoping
    • Inheritance
      • Prototypal Inheritance
      • Call, Apply, and other Functions
      • ES6 Inheritance
      • Resources
    • Custom Node Modules
    • Additional Topics
      • AJAX, Fetch, and Async/Await
      • AJAX w/JSON and Localstorage
        • AJAX w/JSON
        • Local Storage
      • Async module
      • Data Scraping
  • jQuery
    • Intro
      • DOM Manipulation
      • Reddit Practice
      • Styling
      • Events
    • Plugins
    • AJAX
  • APIs
    • Fetch
    • AJAX w/jQuery
    • AJAX w/Fetch
  • Databases
    • Intro to SQL
    • Advanced SQL
    • MongoDB
      • Intro to NoSQL
      • CRUD in MongoDB
      • Data Modeling
      • Intermediate Mongo
  • Node/Express
    • Node
      • Intro to Node
      • Node Modules
      • Node Package Manager (NPM)
    • Express
      • Intro to Express
        • Routes
        • Views
        • Templates
        • Layouts and Controllers
        • CRUD & REST
          • Get and Post
          • Put and Delete
      • APIs with Express (request)
      • APIs with Express (axios)
    • Sequelize
      • Terminology
      • Setup
      • Using Models
      • Seeding Data
      • Validations and Migrations
      • Resources
      • 1:M Relationships
      • N:M Relationships
    • Express Authentication
      • Research Components
      • Code Components
      • Auth in Theory
        • Sessions
        • Passwords
        • Middleware
        • Hooks
      • Auth in Practice
        • Create the User
        • User Signup
        • Sessions
        • User Login
        • Authorization and Flash messages
    • Testing with Mocha and Chai
    • Mongoose
      • Mongoose Associations
    • JSON Web Tokens
      • Codealong
    • Additional Topics
      • oAuth
      • Geocoding with Mapbox
      • Geocoding and Google Maps
      • Cloudinary
      • Websockets with Socket.io
      • SASS
  • Ruby
    • Intro to Ruby
    • Ruby Exercises
    • Ruby Classes
    • Ruby Testing with Rspec
    • Ruby Inheritance
    • Ruby Data Scraping
  • Ruby on Rails
    • Intro to Rails
    • APIs with Rails
    • Asset Pipeline
    • Rails Auth and 1-M
      • Auth Components
    • Rails N:M
    • ActiveRecord Polymorphism
    • Additional Topics
      • oAuth
      • SASS
      • Rails Mailers
      • Cloudinary
      • Jekyll
  • React (Updated 2019)
    • ES6+/ESNext
      • Const and Let
      • Arrow Functions
      • Object Literals and String Interpolation
      • ES6 Recap
      • ES6 Activity
    • Intro to React
      • Create React App
      • Components and JSX
      • Virtual DOM
      • Props
      • Dino Blog Activity
      • Nested Components
      • Lab: LotR
    • React State
      • Code-Along: Mood Points
      • Code-Along: Edit Dino Blog
      • Lab: Simple Calc
      • Lifting State
    • React Router
      • Browser History/SPAs
      • React Router (lesson and full codealong)
      • Router Lab
    • Fetch and APIs
      • APIs with Fetch and Axios
      • Fetch the Weather
    • React Hooks
    • React LifeCycle
      • Lab: Component LifeCycle
    • React Deployment
    • Additional Topics
      • React Frameworks
        • Material UI Theming
      • Typescript
        • More Types and Syntax
        • Tsconfig and Declaration Files
        • Generics with Linked List
      • Redux
      • TypeScript
      • Context API
      • React Native
  • Meteor
  • Deployment and Config
    • Deploy - Github Pages
    • Deploy - Node/Sequelize
    • Deploy - Node/MongoDB
    • Deploy React
    • Deploy - Rails
      • Foreman (Environment Variables)
    • Deploy - AWS Elastic Beanstalk
    • Deploy - S3 Static Sites
    • Deploy - Django
    • Deploy - Flask
  • Data Structures and Algorithms
    • Recursion
    • Problem Solving - Array Flatten
    • Binary Search
    • Algorithm Complexity
    • Stacks and Queues
    • Bracket Matching
    • Ruby Linked Lists
      • Sample Code
      • Beginner Exercises
      • Advanced Exercises
    • JS Linked Lists
      • Sample Code
      • Beginner Exercises
      • Beginner Solutions
    • Hash Tables
    • Intro to Sorting
    • Insertion Sort
    • Bucket Sort
    • Bubble Sort
    • Merge Sort
    • Quick Sort
    • Heap Sort
    • Sorting Wrapup
    • Hashmaps
    • Trees and Other Topics
  • Python
    • Python Installation
    • Intro to Python
    • Python Lists
    • Python Loops
    • Python Dictionaries
    • Python Sets and Tuples
    • Python Cheatsheet
    • Python Functions
    • Python Classes
    • Python Class Inheritance
    • Intro to Flask
    • Intro to SQLAlchemy
      • Flask and SQLAlchemy
    • Using PyMongo
    • Intro to Django
    • CatCollector CodeAlong
      • URLs, Views, Templates
      • Models, Migrations
      • Model Form CRUD
      • One-to-Many Relations
      • Many-to-Many Relations
      • Django Auth
    • Django Cheatsheet
    • Django Auth
    • Django Polls App Tutorial
    • Django School Tool Tutorial
    • Django 1:M Relationships
    • Custom Admin Views
    • Data Structures and Algorithms
      • Recursion
      • Binary Search
      • Stacks and Queues
      • Linked Lists
      • Binary Trees
      • Bubble Sort
      • TensorFlow & Neural Networks
    • Adjacent Topics
      • Raspberry Pi
      • Scripting
  • Assorted Topics
    • History of Computer Science
    • Regular Expressions
    • Intro to WDI (Course Info)
    • Being Successful in WDI
    • Internet Fundamentals
      • Internet Lab
    • User Stories and Wireframing
      • Wireframing Exercise: Build an Idea
    • Post WDI
      • Learning Resources
      • Deliverables -> Portfolio
      • FAQ
  • Projects
    • Project 1
    • Project 2
    • Project 3
      • Project 3 Pitch Guidelines
    • Project 4
    • Past Projects
      • Project 1
      • Project 2
      • Project 3
      • Project 4
      • Portfolios
    • Post Project 2
    • MEAN Hackathon
      • Part 1: APIs
      • Part 2: Angular
    • Portfolio
  • Web Development Trends
  • Resources
    • APIs and Data
    • Tech Websites
    • PostgreSQL Cheat Sheet
    • Sequelize Cheat Sheet
    • Database Administration
  • Archived Section
    • (Archived) ReactJS
      • Intro to React
        • Todo List Codealong
        • Additional Topics
      • Deploy React
      • React with Gulp and Browserify
        • Setting up Gulp
        • Additional Gulp Tasks
      • React Router
        • OMDB Router
        • OMDB Search
        • Additional Resources
      • React Animations
        • CSS Animations
    • AngularJS
      • Intro to AngularJS
        • Components and SPA
        • Create an Angular App
      • Angular Directives and Filters
      • Angular Animation
      • Angular Bootstrap Directives
        • Bootstrap Modals
      • Angular $http
      • Angular Services
        • Service Recipes
        • ngResource
        • Star Wars Codealong
      • Angular Routing
      • Angular + Express
      • Angular Authentication
        • Additional Topics
      • Angular Components
      • Angular Custom Filters
      • Angular Custom Directives
Powered by GitBook
On this page
  • Getting Started
  • Adding Dependencies
  • Creating a Film Service
  • Using the Films service
  • Why use a Service?
  • Conclusion
  • Finished Code (Example)
  1. Archived Section
  2. AngularJS
  3. Angular Services

Star Wars Codealong

Getting Started

Create a new folder called starwarsapp with the following folders and files:

- starwarsapp
  - js
    - app.js
  - index.html

Setup the HTML page with the usual tags.

Adding Dependencies

First thing's first, let's add the correct dependencies inside the head tags. Additionally, add Bootstrap if you wish.

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular-resource.js"></script>
<script src="js/app.js"></script>

Note that in order to use $resource, we need to include an additional script. We'll also need to inject the dependency (named ngResource) into our app.

In app.js:

angular.module('StarWarsApp', ['ngResource'])

.controller('FilmsCtrl', ['$scope', function($scope) {

}]);

Make sure to add ng-app and ng-controller directives to index.html and test the app before continuing.

Creating a Film Service

Now, we're going to create a service for accessing Star Wars films using the factory recipe. This service will provide an object we can inject into controllers, and it'll provide functions for interacting with the Star Wars API.

We'll create this service in the same file for now.

In app.js, we'll create a factory and inject it into the controller.

angular.module('StarWarsApp', ['ngResource'])

.factory('Films', ['$resource', function($resource) {
  return $resource('http://swapi.co/api/films/:id');
}])

.controller('FilmsCtrl', ['$scope', 'Films', function($scope, Films) {
  console.log(Films);
}]);

When we refresh the page, the contents of the Films service should be logged to the browser console.

Using the Films service

In order to use the Films service, we can call get and query from the controller. If we had a complete RESTful service, we could also call save and remove.

In app.js:

app.controller('FilmsCtrl', ['$scope', 'Films', function($scope, Films) {
  $scope.films = [];
  Films.query(function success(data) {
    $scope.films = data;
  }, function error(data) {
    console.log(data);
  });
}]);

In index.html:

<div class="well" ng-repeat="film in films">
  <h2>{{film.title}}</h2>
  <p>{{film.opening_crawl}}</p>
</div>

But wait! You'll notice that an error appears when you reload the page. That's because $resource assumes that the query function will return an array, but the Star Wars API returns an object. Luckily, we can customize the service with our own functions. Let's modify the service like so:

.factory('Films', ['$resource', function($resource) {
  return $resource('http://swapi.co/api/films/:id', {}, {
    query: { isArray: false }
  });
}])

This will return a resource with a modified query method.

Try it: Use the get method from the Films service to retrieve the second film (id of 2). If you're not sure how to pass the film id in, consult the documentation for $resource.

Why use a Service?

Here's a trivial example of customizing our Films resource, by specifying different function names.

app.factory('Films', ['$resource', function($resource) {
  return $resource('http://swapi.co/api/films/:id', {}, {
    all: { method: 'GET', cache: false, isArray: false },
    get: { method: 'GET', cache: false, isArray: false },
    save: { method: 'POST', cache: false, isArray: false },
    update: { method: 'PUT', cache: false, isArray: false },
    delete: { method: 'DELETE', cache: false, isArray: false }
  });
}]);

Note that for a lot of APIs, isArray will be set to true for the GET all endpoint. This isn't the case for the Star Wars API. We also set the cache to false, but it could be set to true for performance improvements. We also may want to customize the all endpoint in the future, if we want to limit results (imagine getting all Facebook users when calling .all).

Conclusion

We've used services when working with $http and Bootstrap modals, and we just made our own. By doing so, we've isolated business logic out of our controllers, so that they can focus mainly on initializing and manipulating data.

Later, we'll add routing to this Star Wars app and implement all of the CRUD functions.

Finished Code (Example)

Here's some example finished code. This will likely not match yours, but try playing around with the example and see if you can pull other resources from the Star Wars API!

index.html:

<!DOCTYPE html>
<html ng-app="StarWarsApp">
<head>
  <title>Star Wars App</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular-resource.js"></script>
  <script src="js/app.js"></script>
</head>
<body ng-controller="HomeCtrl">
  <div>
    <input type="integer" ng-model="movieId">
    <button ng-click="getMovie(movieId)">Get</button>
    <button ng-click="getAll()">All</button>
  </div>

  <div ng-if="loading">
    Loading...
  </div>

  <div ng-if="!loading" ng-repeat="film in films">
    <h1>{{film.title}}</h1>
    <p>{{film.opening_crawl}}</p>
  </div>
</body>
</html>

js/app.js:

var app = angular.module('StarWarsApp', ['ngResource']);

app.factory('FilmsFactory', ['$resource', function($resource) {
  // use the colon syntax to specify the id parameter in the url.
  var url = 'http://swapi.co/api/films/:id';

  return $resource(url, {}, {
    // overwrite the isArray value when querying for movies
    query: { isArray: false }
  });
}]);

app.controller('HomeCtrl', ['$scope', 'FilmsFactory', function($scope, FilmsFactory){
  $scope.movieId = 1;
  $scope.films = [];
  $scope.loading = false;

  $scope.getAll = function() {
    $scope.loading = true;
    FilmsFactory.query(function success(data) {
      $scope.films = data.results;
      $scope.loading = false;
    }, function error(data) {
      console.log('error');
      $scope.loading = false;
    });
  };

  $scope.getMovie = function(id) {
    $scope.loading = true;
    FilmsFactory.get({ id: id }, function success(data) {
      // placing data in an array in order for ng-repeat to work on a single movie
      $scope.films = [data];
      $scope.loading = false;
    }, function error(data) {
      console.log('error');
      $scope.loading = false;
    });
  };
}]);
PreviousngResourceNextAngular Routing

Last updated 3 years ago

You may be wondering why we're using a service for a one-line resource. Usually, resources are more complex and can be customized as you see fit. Take a look at the and see what can be customized. Even if we didn't add additional customizations, the service allows many controllers to access the resource as a singleton.

documentation for $resource