Blog>
Snippets

Injecting Services in a Standalone Component

Provide an example of how to inject a service into a standalone component, such as a logging service, without relying on an NgModule.
// Define the LoggingService class

class LoggingService {
  log(message) {
    console.log('Log: ', message);
  }
}
This piece of code defines a simple LoggingService class with a log method that outputs a message to the console.
// Define the Injector class as a minimal DI container

class Injector {
  static resolve(target) {
    // Dependencies are static properties of the target class
    const deps = target.dependencies || [];
    const instances = deps.map(dep => new dep());
    return new target(...instances);
  }
}
This code defines a basic Injector class that can be used as a minimalistic dependency injection container. It uses a static resolve method to instantiate dependencies defined as static properties of the target class.
// Define the StandaloneComponent class with a dependency on LoggingService

class StandaloneComponent {
  static dependencies = [LoggingService];

  constructor(logService) {
    this.logService = logService;
  }

  performAction() {
    this.logService.log('Action performed in StandaloneComponent');
  }
}
Here we define a StandaloneComponent class that has a dependency on LoggingService. The dependencies are statically defined and are intended to be resolved by the Injector.
// Usage Example

const componentInstance = Injector.resolve(StandaloneComponent);
componentInstance.performAction();
This is an example of how to use the Injector to create an instance of the StandaloneComponent and call its performAction method, which utilizes the injected LoggingService instance.