Angular Services
What is a service?
- Services provide data/features.
- Data/features can be used in more than one place.
Why use services?
- Services can get us data.
- Can be either the data itself, or directions to get the data.
- Typically one service per type of data.
- Can be used in multiple places.
Angular Services
- Lazily Instantiated - Only created when they are needed in a controller.
- Singletons.
What is a singleton?
A singleton is a constructor function that only ever returns one
instance of an object
Not a Singleton
var myCalculator = getCalculator();
myCalculator.setValue(10);
myCalculator.getValue(); // 10;
var newCalculator = getCalculator();
newCalculator.getValue(); // not the same as myCalculator
Singleton
var myCalculator = getCalculator();
myCalculator.setValue(10);
myCalculator.getValue(); // 10;
var newCalculator = getCalculator();
newCalculator.getValue(); // 10;
Singleton
Will always give you the same data.
Singletons are literally the same object.
Non-singletons
Won't always give you the same data.
Non-singletons are copies of the same object.
Why Singletons?
- To send data between two different callers.
- To have the same data in both places.
- To have one source of truth
Lazily Instantiated
View
Controller
Service
How to use
Angular services
Use services for:
- Code that doesn't belong to one particular view.
- Code that needs to be used in multiple controllers.
Services and Controllers
User Service
Home Controller
Profile Controller
Profile View
Home View
Controller
- Clicking the login button
- Showing the username in the corner
- Displaying a list of to do items
- Showing the weather today
Service
- Sending a request to the server to login a user
- Getting user information from the database
- Retrieving a list of to dos from the database.
- Getting the weather from a weather API.
Built in Angular services
- $http - Send http requests and receive data back.
- $location - Can tell you where you are in an Angular app and send you to other pages.
- $log - Console.log for Angular
- $filter - Can be used to filter data on a page.
Angular Services
By Brett Caudill
Angular Services
- 751