Explain the steps for creating a services in Angular 2 - GeeksforGeeks

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 STATEMENTimport { 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.tsapp.module.tsimport { 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 {}
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.tsapp.component.tsimport { 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 {}
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.
AngularJS-Questions
Blogathon-2021
Picked
AngularJS
Blogathon
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Angular Libraries For Web Developers
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
How to Call or Consume External API in Spring Boot?
Re-rendering Components in ReactJS
SQL Query to Insert Multiple Rows
Python NOT EQUAL operator
Difference Between Local Storage, Session Storage And Cookies