Service Pattern

In Angular, the Service Pattern is a design pattern used to create reusable services that can be injected into various components throughout your application.

These services encapsulate business logic, data manipulation, or interaction with external resources like APIs.

They promote code reusability, maintainability, and separation of concerns.

Here's a basic example of creating a service in Angular:

// service-example.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root' // Specifies that Angular should provide this service at the root level
})
export class ExampleService {

  constructor() { }

  // A method in the service to perform some logic
  greet(name: string): string {
    return `Hello, ${name}!`;
  }

}

In this example:

  • @Injectable() decorator marks the class as a service that can be injected into other components or services.

  • providedIn: 'root' ensures that Angular creates a single, shared instance of the service and provides it throughout the application.

  • greet() method is an example of a function within the service that performs some logic. Here, it simply takes a name and returns a greeting message.

Now, let's see how you can use this service in a component:

// app.component.ts

import { Component } from '@angular/core';
import { ExampleService } from './service-example.service';

@Component({
  selector: 'app-root',
  template: `
    <h1>{{ message }}</h1>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  message: string;

  constructor(private exampleService: ExampleService) {
    this.message = this.exampleService.greet('John');
  }
}

In this component:

  • We import the ExampleService and inject it into the component's constructor.

  • Inside the constructor, we use the service's greet() method to generate a greeting message, and assign it to the message property.

By using the Service Pattern, you can keep your components lean and focused on presentation logic while delegating business logic to services, which can be easily shared and reused throughout your Angular application.

Last updated