Explain the steps for creating a services in Angular 2
Last Updated :
11 Sep, 2021
If you've ever constructed a component, you're aware that the component contains an executable code, allowing you to include any functionality that you want. The task of the component is to enable the user experience, which will interact with the user. The component will act as an intermediate between business logic & the application view. However, the official Angular style guide indicates limiting the logic of a component to what is needed for the view. The services should handle all other logic. The code in the component's code is mostly used to control and manipulate the user interface. It should call services to provide functionality that isn't directly related to the UI. Thus, if the required functionality isn't required by the view, you should consider building a service.
Services are used to create variables/data that can be shared and can be used outside the component in which it is defined. A service is essentially a class having a specific goal. A service can be a variable, function, or feature that an application needs. We often use services to provide functionality that is independent of components, to transfer data or logic between components, or to encapsulate external interactions like data access. The code becomes easier to test, debug, and reuse by transferring these activities from the component to the service. A service is a reusable piece of functionality that may be used by a variety of components. Services can be used to avoid rewriting the same code, it can be written once and injected into all the components that use that specific service.
It is necessary to have a single responsibility for service. You shouldn't just put all of your shared functionality into a single service in your app. Services are additional bits of functionality that can be delivered when and where they're required in the app. We accomplish this with Angular by integrating our services with the dependency injection system. For generating the service, we can follow 2 ways:
- By creating it manually to perform the specific tasks, we need to set up & configure the service.
- By using Angular CLI, it will set up all the necessary configurations for the service automatically.
We will understand both approaches through examples in a sequence.
Method 1: Using a manual way to generate the service:
We will create the service class, use a decorator to describe the metadata, then import what we require. These are the same fundamental techniques we use to manually construct our components and custom pipe.
Syntax:
import { Injectable } from '@angular/core';
@Injectable()
export class ServiceName {
}
Let’s look at the code for building a basic service whose function is to return the course list a certain institute has to offer.
Step 1: Create a class CoursesService and save the file as courses.service.ts. Don’t forget to export the class so that any component can make use of the service. Let’s add our getdata method to this class.
export class CoursesService { // SERVICE CLASS
constructor() { }
getdata(): string[] {
return ['C','C++', 'JAVA', 'Python'];
}
}
Step 2: The service metadata is then decorated with a decorator. We use the Injectable decorator while creating services. Because the decorator is a function, it should be surrounded by an open and closing parenthesis.
@Injectable() // DECORATOR
export class CoursesService {
constructor() { }
getdata(): string[] {
return ['C','C++', 'JAVA', 'Python'];
}
}
Step 3: Ensure that the correct imports are defined. Now our service class is ready.
courses.service.ts
// IMPORT STATEMENT
import { Injectable } from '@angular/core';
@Injectable()
export class CoursesService {
constructor() { }
getdata(): string[] {
return ['C','C++', 'JAVA', 'Python'];
}
}
Step 4: Now, we need to inject our service. The service can be injected in two ways.
- Injecting as a global service: Inject the service into the root module to make it a global service. Any component inside this module can make use of this service now.
app.module.ts
import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { AppComponent } from "./app.component";
import { CoursesService } from "src/services/courses.service";
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [CoursesService], // FOR GLOBAL SERVICE
bootstrap: [AppComponent],
})
export class AppModule {}
- Injecting as a local service: Inject the service directly into the component to inject as a local service.
app.component.ts
import { Component } from "@angular/core";
import { CoursesService } from "src/services/courses.service";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
providers: [CoursesService], // FOR LOCAL SERVICE
})
export class AppComponent {}
Step 5: In this step, we need to import the service to the component and use the method.
app.component.ts
import { Component } from "@angular/core";
import { CoursesService } from "src/services/courses.service";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
})
export class AppComponent {
courses: string[];
constructor(private _coursesService: CoursesService) {}
ngOnInit() {
this.courses = this._coursesService.getdata();
}
}
Step 6: Update the HTML component to render it.
app.component.html
<h2>Course List</h2>
<p *ngFor="let c of courses">{{ c }}</p>
Step 7: Run 'ng serve' to start the app. We will see the output as below:
Method 2: Using Angular CLI to generate the service. We will be using the same example here to generate the service in Angular CLI.
Step 1: We will use Angular CLI to create a service. This approach is recommended as there are fewer chances of making errors. It only takes one command to do the task. We will follow the below syntax to create a service.
Syntax:
ng g service courses
It will generate the service code skeleton as below:
import { Injectable } from '@angular/core';
@Injectable()
export class ServiceName {
constructor() { }
}
Step 2: After the service is created, we have to include it in the providers of app.module.ts
providers: [CoursesService],
Here, the first letter of the service name should be capital followed by Service written without any space.
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { CoursesService } from './courses.service';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [CoursesService], //FOR GLOBAL SERVICE
bootstrap: [AppComponent]
})
export class AppModule {}
Step 3: In app.component.ts, make the following changes:
import the service among the rest of the required imports.
import { CoursesService } from './courses.service';
Create a variable of any type: courses without mentioning any type.
In constructor define a property of the Service type
constructor(private _coursesService: CoursesService) {}
Also, create a ngOnInit method:
ngOnInit() {
this.courses = this._coursesService.getdata();
}
After completing the above tasks, the app.component.ts file will be like the following:
app.component.ts
import { Component } from '@angular/core';
import { CoursesService } from './courses.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
courses: string[];
constructor(private _coursesService: CoursesService) {}
ngOnInit() {
this.courses = this._coursesService.getdata();
}
}
Step 4: In this step, we will add our method to the service.
courses.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class CoursesService {
constructor() { }
getdata(): string[] {
return ['C','C++', 'JAVA', 'Python'];
}
}
Step 5: In app.component.html we will print the data stored in courses.
app.component.html
<h2>Course List</h2>
<p *ngFor="let c of courses">{{ c }}</p>
Step 6: Run 'ng serve', the following output will be displayed.
Similar Reads
Creating an injectable service in Angular
In Angular, services are a great way to share data, functionality, and state across different components in your application. Services are typically injected into components and other services as dependencies, making them easily accessible and maintainable. Mostly services are used to create functio
3 min read
Creating An Interface In Angular
In Angular, an interface is a TypeScript feature that defines the shape or structure of an object. It helps developers enforce type safety by specifying what properties and types an object must have. Interfaces do not generate JavaScript code but are used during the development phase to ensure that
4 min read
Explain the Architecture Overview of Angular ?
Angular is a client-side front-end framework developed by a team of developers at Google based on Typescript. It is used for building dynamic and single-page web applications (SPAs). Also, Angular is a versatile framework for building web applications and offers a wide range of features and tools to
6 min read
What is the Difference Between factory and service in AngularJS ?
AngularJS is a JavaScript-based framework. It can be used by adding it to an HTML page using a <script> tag. AngularJS helps in extending the HTML attributes with the help of directives and binding of data to the HTML with expressions. In this article, we will explore the differences between t
4 min read
Explain the purpose of Router services in Angular.
The Router service in Angular is an important component that enables navigation within our single-page application (SPA). It involves mapping URLs to different components or views within the application and rendering the appropriate content based on the requested URL. When a user interacts with navi
6 min read
Using a http service in Angular 17 with standalone components
In Angular 17, they've introduced standalone components, which change how you build and organize Angular applications. These components are self-sufficient and can be used on their own without being tied to a specific NgModule. But, sometimes, when you're working with these standalone components, yo
3 min read
How to Create a new module in Angular ?
Modules are most important when it comes to building strong and scalable Angular applications. They help organize your code, promote modularity, and improve maintainability. It encourages collaboration among developers by grouping related components, directives, pipes, and services. In this article,
3 min read
Is Angular Dead? The Truth About Angular in 2025
The question "Is Angular dead?" has been a repetitive topic in discussions and within the developer community for years. As we step into 2025, it's important to assess Angular's current state, its evolution, and its standing in the competitive landscape of front-end frameworks. This comprehensive an
10 min read
How to Register Services with the Providers Array in Angular?
To register services with the provider's array in Angular, you first generate a service using the Angular CLI. Then, you can register the service in the providers array within the module (app.module.ts) or component where the service is needed. Once registered, the service can be injected into any c
3 min read
What is the purpose of providedIn in Angular services?
When building Angular applications, you'll often need to share data and logic across different components. This is where services come into play. Services are an easy way to encapsulate functionality and make it available wherever it's needed in your app. But as your application grows, managing the
3 min read