Blog>
Snippets

Implementing a Plugin Lifecycle in Angular

Create an interface for the initialization and destruction life cycle hooks for a plugin, and demonstrate how to invoke these hooks in Angular services.
export interface PluginLifecycle {
  initialize(): void;
  destroy(): void;
}
Defines an interface with initialization and destruction lifecycle hooks for a plugin.
import { Injectable, OnDestroy } from '@angular/core';
import { PluginLifecycle } from './plugin-lifecycle.interface';

@Injectable({
  providedIn: 'root'
})
export class PluginService implements OnDestroy, PluginLifecycle {

  constructor() {
    this.initialize(); // Call initialize on service instantiation
  }

  initialize(): void {
    // Plugin initialization logic goes here
    console.log('Plugin initialized.');
  }

  ngOnDestroy(): void {
    this.destroy(); // Call destroy before the service is destroyed
  }

  destroy(): void {
    // Plugin destruction logic goes here
    console.log('Plugin destroyed.');
  }
}
Implements the PluginLifecycle interface in an Angular service, ensuring that the plugin is initialized when the service is instantiated and destroyed when the service is cleaned up by Angular's garbage collection.