As the following feature request for Angular is still open I'd "simply" like to create my own version of the @Optional() decorator that can take/return a default value in case the injected property has not been provided: https://github.com/angular/angular/issues/25395
I would like to avoid the following:
export class ExampleComponent{
constructor(
@Optional() private exampleService?: ExampleService
) {
if (!this.exampleService) {
this.exampleService = new FallbackExampleService();
}
}
Instead I'd like to write something like this:
export class ExampleComponent{
constructor(
@OptionalWithDefault(new FallbackExampleService()) private exampleService: ExampleService
) {}
}
Unfortunately the original code inside the Angular project in my eyes is not that easy to follow. You can find it here: https://github.com/angular/angular/blob/main/packages/core/src/di/metadata.ts#L105
and its underlying method makeParamDecorator() here:
https://github.com/angular/angular/blob/main/packages/core/src/util/decorators.ts#L99
Has maybe anyone of you already done something similar?