Blog>
Snippets

Optional Injection Token Dependencies

Present the usage of @Optional decorator to handle the scenario where an InjectionToken might not have a provided value.
import { Injectable, Optional, InjectionToken, inject } from '@angular/core';

// Define an injection token for the dependency
const MY_DEP_TOKEN = new InjectionToken('MyDep');

@Injectable({
  providedIn: 'root'
})
export class MyService {

  // Use @Optional to allow the dependency to be missing
  constructor(@Optional() @Inject(MY_DEP_TOKEN) private myDep: any) {
    if(this.myDep) {
      console.log('Dependency provided:', this.myDep);
    } else {
      console.log('No dependency provided.');
    }
  }

}
This code defines an Angular service called MyService which attempts to inject a dependency associated with the token MY_DEP_TOKEN. The @Optional decorator is used to indicate that the dependency is not required and the service should handle the case where it's not provided. Inside the constructor, the code checks if the dependency was supplied and logs an appropriate message.