One of the modules I imported provides a service with an optional dependency. Although it being optional didn't affect my application, as it just prevented any errors from occurring when not present. Here's an example:
import { FooModule } from './foo.module';
import { BarService } from './bar.service';
// other imports and logic omitted...
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
FooModule.forRoot(options),
],
providers: [
BarService,
],
bootstrap: [AppComponent],
})
export class AppModule { }
In the code snippet above, the FooModule
includes a FooService
that can be utilized in different parts of the app. The FooService
has an optional dependency:
export interface IBarService {
bar: (x: string) => string;
}
export const BarService = new InjectionToken<IBarService>('any compatible bar service provider');
@Injectable()
export class FooService {
constructor(
@Optional() @Inject(BarService) private barService?: IBarService,
) {
console.log(barService)
}
}
I have provided the optional dependency (BarService
) in the initial code block. However, I noticed that it wasn't being passed to the FooService
within the FooModule
.
Both services share the same injection name: BarService
.
Despite this, when running the app, the console shows the barService
as null
.