Introduction

Services are a layer which contain the business logic of an application. Services in Angular exist in order to differentiate components from other logic in the application.

Since components deal with the view, binding, methods, and properties, services relieve some of the pressure off of components by allow components to hand off some tasks to the service. Furthermore, it allows the logic in the service layer to be reused by other components.

How to create a service file

A service file can be created by using the Angular CLI by typing the following command in your project’s directory:

ng g s nameOfService

Dependency Injection (DI)

When a component needs a service, the service then becomes a dependency. The service is then injected into the component through the components constructor. This is called Dependency Injection.

Suppose we have a user component (user.component.ts) and a user service (user.service.ts), Dependency Injection would be done in the following way:

“Link (Dependency Injection in the Component)”

As you can see from the image above, we service is injected into the constructor of the component. Therefore, when the component is initialized, an instance of the service is initialized as well.

The service file would look as follows:

“Link (A Service File)”

You might have noticed that in the service class file there is a decorator at the top of the file called @Injectable. This decorator acts as a flag for a class. This flag signals to other parts of the application the availability of the class “to be provided and injected as a dependency."[1] 'root' tells Angular to create only one instance of this service class and to allow it to be injected into any class that requests it in the application. Tree shaking is implemented here by allowing Angular to take out the service if it is not used in the compiled application, thereby optimizing it.

You can also register a service class within a provider inside a module. This will make the service available to all components that are part of the module. This can be done in the following manner:

@NgModule({
    providers: [
        AuthService,
        UserService
    ]
})

Services can also be registered in a component inside the component’s decorator as follows:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  providers: [RegisterService]
})

While services should be separate from components, should you need to combine them in one file, services should come before components. Otherwise, Angular will throw a “run-time null reference error."[2]

[1] https://angular.io/api/core/Injectable
[2] https://angular.io/guide/dependency-injection