Singleton Pattern

In Angular, the Singleton Pattern is often implemented using Angular services.

Angular services are singletons by default, meaning Angular creates only one instance of a service and shares it throughout the application.

This makes them ideal for managing shared state, performing common tasks, or encapsulating reusable functionality.

Here's an example of implementing a singleton service in Angular:

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

@Injectable({
  providedIn: 'root'
})
export class MySingletonService {
  private sharedData: any;

  constructor() {
    // Initialize shared data if needed
    this.sharedData = {};
  }

  // Method to set shared data
  setSharedData(data: any) {
    this.sharedData = data;
  }

  // Method to get shared data
  getSharedData() {
    return this.sharedData;
  }

  // Other methods and properties can be added as needed
}

In this example:

  • @Injectable decorator is used to mark the class as a service.

  • providedIn: 'root' option in the @Injectable decorator ensures that Angular creates a single instance of the service for the entire application.

  • The MySingletonService class contains some shared data (sharedData) and methods to manipulate it.

  • You can inject MySingletonService into any component, directive, or other service in your Angular application.

Here's how you would use the MySingletonService in a component:

import { Component } from '@angular/core';
import { MySingletonService } from './my-singleton.service';

@Component({
  selector: 'app-example',
  template: `
    <div>{{ sharedData }}</div>
    <button (click)="updateSharedData()">Update Shared Data</button>
  `
})
export class ExampleComponent {
  sharedData: any;

  constructor(private mySingletonService: MySingletonService) {
    // Retrieve shared data initially
    this.sharedData = this.mySingletonService.getSharedData();
  }

  updateSharedData() {
    // Update shared data
    this.mySingletonService.setSharedData({ example: 'Updated data' });
    // Update local copy for display
    this.sharedData = this.mySingletonService.getSharedData();
  }
}

In this component:

  • We inject MySingletonService into the constructor.

  • In the constructor, we initialize the sharedData property with the data retrieved from the service.

  • The updateSharedData() method demonstrates how to update the shared data via the service.

By using Angular services, you're effectively utilizing the Singleton Pattern, ensuring that there's only one instance of the service throughout the Angular application.

Last updated