Angular 2.0 – Services

A service is typically a class which have a specific, well-defined purpose. It is a broad category that holds a value, feature or a function that the application needs.
Examples are Logging Service, Data Service etc.

Angular do not provide any base class for services nor any place to register them. Yet they are very important and fundamental for any Angular Application.

Services are used by Components by Dependency Injection (DI).

Component should only focus on user’s experience. Presents methods and properties for data binding and application logic for the view. It delegates all the other work to services. However it is not mandatory rule of Angular but it is a good practice to refactor your code making it simple for debugging and simple to read and understand.




Example:

import { Injectable } from ‘@angular/core’;

@Injectable()
export class userService
{
private usersPromise: Promise. = Promise.Resolve({‘George’,’Stephen’,’Leo’});
getUsers()
{
return usersPromise;
}
}

Tip:
If we are going to get information out of an API or server it would makes sense that we return a Promise. Later in the tutorial you will learn how we usually return data as a Promise or as an Observable.