The service is a good option when you need sharing data through the application or do some task such connect some other site, call a REST, etc.

You can create a service using the @angular/cli by the command:

ng g service myservice

Or by yourself creating a new file inside the folder you choose. On the top of the class you should to declare the @Injectable. It is the Dependence Injection (DI) responsible to instantiate the object.

import { Injectable } from '@angular/core';
@Injectable()
export class MyService { ... }

If the service is specific to your component you just need to declare the service inside the 'provider' of your component to be available to Angular inject this service. Also the constructor should declare parameters which services will be used. Some github examples you can see here: [1], [2], [3] and [4]

@Component({
     selector: 'my-app',
     templateUrl: './my-app.component.html',
     providers: [MyService]
})
export class MyComponent {
     constructor(private myservice:MyService){}
... }

 

If it is a service that you need to use in many situations in your app and, for example, need to preserve the state of the data, you need to declare this service in a higher level. It is necessary because, when you navigate to other component and get back, the state will be restarted. Then, one example is to declare inside the app.component.ts.

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   providers: [MyService]
})
export class AppComponent implements OnInit { ... }

Dependency Injector

The Angular dependency injector is a hierarchical injector. Then you create a service to a component it will be available to all its child components. All of them will have the same instance of the service.

  1. The highest level is the AppModule. Then, any instance declared in this level will be available to all the app.
  2. The second level, one level below is the AppComponent. The instance created in this level will be available to all of its children, but not to the AppModule level. The instance is propagate only to the lowest level.
  3. The last level, the lowest level, where there are no children, the instances create in this level will be available only to this component. And if in a higher level the same service is provided, the local instance will be override.

There are two types of the hierarchies in Angular. When you use @Injection or @NgModule to the injection, it is called ModuleInjector. However, if you use @Directive or @Component to provide the injection it is called ElementInjector.

References