How to generate a service using the Angular CLI?

A service can be a value, function, or feature that can be used by any component in the Angular application. Like any other class, the service performs a well-defined and specific task and ensures code reusability. Angular components handle data binding between the view and application logic. Services don’t take part in building the application logic. Instead, they can be used for tasks like input validation and retrieving information from the server. Angular uses dependency injection to give access to services to different app components.

Syntax

Two files are generated to implement any service using the CLI (command line interface). The my-service.service.ts file has the following syntax.

import { Injectable } from '@angular/core';
@Injectable({
providedIn:'root'
})
export class MyServiceService {
constructor() { }
}
  • Lines 1–5: For a service to be available to a component in the application, it should be made available to the dependency injection system. We do this by importing the Injectible decorator, where @Injectible defines a class as a service and registers it with the root injector using providedIn:'root'. With this, we create a single shared instance of the service, which can be used by any component class.

  • Lines 6–8: Here, export class MyServiceService ensures that the service class can be imported into other components. We can implement our logic here.

The file below, called my-service.service.spec.ts, is created by the CLI. This file is used for testing services.

import { TestBed } from '@angular/core/testing';
import { MyServiceService } from './my-service.service';
describe('MyServiceService', () => {
let service: MyServiceService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(MyServiceService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
  • Lines 1–2: These lines import the TestBed testing utility for unit testing and the service we create— MyServiceService.

  • Lines 4–10: Here, describe('MyServiceService', () => {}) defines a test suite called MyServiceService using the Jasmine library. The let service: MyServiceService; part stores an instance of the service, while the beforeEach function in Jasmine is executed before each test case. TestBed.configureTestingModule configures the test module, while TestBed.inject injects the service inside the test case.

  • Lines 12–14: In this line, Jasmine’s expect function checks whether the MyServiceService service has been created.

What is the Angular CLI?

The Angular CLI runs commands for creating and maintaining components, services, etc.

The following command can be run to install the Angular CLI. Press “Runand paste the following command in the terminal to install the Angular CLI.

npm install -g @angular/cli --interactive=false
Terminal 1
Terminal
Loading...

Using the Angular CLI to generate services

The following command creates a new service in our Angular application. Run the terminal below and paste the command given below to generate a service. Change the service_name to whatever you want.

ng generate service service_name

Next, enter the following command, and you’ll be able to see that your service files exist in the /home/angular/src/app folder.

ls src/app/

First, create the service, then check whether it has been created.

Terminal 1
Terminal
Loading...

The following code shows how MyServiceService is used inside the app component.

import { Component } from '@angular/core';
import { MyServiceService } from './my-service.service';
@Component({
selector: 'educative-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
app_title:string;
heading_name:string;
hero_body_text:string;
register_service_text:string;
constructor(private myService:MyServiceService){
this.app_title = 'educative_app';
this.heading_name = this.myService.heading_name;
this.hero_body_text = this.myService.hero_body_text;
this.register_service_text = this.myService.register_service_text;
}
}
  • Lines 1–2: In these lines, we make the imports, i.e., the Component decorator and the MyServiceService class.

  • Lines 4–8: The @Component defines the metadata for the component, while templateUrl and styleUrls tell which HTML files and style sheets, respectively, are associated with this component. The educative-app selector can be used to incorporate this component in the HTML files.

  • Lines 9–13: These lines define the Appcomponent class and all its string variables.

  • Lines 15–19: The constructor runs and initializes the values of this component’s variables with those from the service class, while private myService:MyServiceService performs a dependency injection and injects an instance of MyServiceService into the app component.

<!DOCTYPE html>
<HTML>
<body>
<div class="center_content">
<img src="./assets/images/educative_logo.png">
<p class = "app_main_heading">
{{ hero_body_text }}
</p>
<div style="width:30px; height:30px;"></div>
<p class = "app_sub_heading">
{{ register_service_text }}
</p>
</div>
</body>
</HTML>
<router-outlet></router-outlet>

The code above is the template file associated with the app component. It demonstrates how the app component’s data is utilized inside the HTML file. The template expression {{ hero_body_text }} is for displaying the value of the hero_body_text property from the AppComponent class in the HTML file.

Click the “Run’’ button to see how dependency injection is used to display text on the landing page of the Angular application. It might take some time to get the server up and running.

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
Running Example

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved