Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a default value for an injectable class

Here is what I want to do:

@Injectable()
export class MyInjectableClass {
   constructor(timeout: number = 50) {
   }
}

What I want to accomplish is timeout being set to 0 when it is injected, but when it is constructed manually, the calling code can set any value it wants.

That doesn't work because the injector cannot inject a "number", and doesn't realize that there's a default it could use. This also doesn't work:

@Injectable()
class MyInjectableClass {
   constructor(@Optional() timeout: number = 50) {
   }
}

That doesn't work because reasons.

What does work is

export class MyInjectableClassOptions {
   timeout: number,
}

@Injectable()
export class MyInjectableClass {
   constructor(@Optional() options?: MyInjectableClassOptions) {
      const timeout = options? options.timeout : 50;
   }
}

But man, is that ugly and elaborate. Tell me there is another possibility.

like image 277
Michael Lorton Avatar asked Oct 26 '25 14:10

Michael Lorton


1 Answers

You can use an InjectionToken to inject simple value.

Something like

export const MY_OPTION = new InjectionToken<number>('my-option');

And then in your module

providers: {provide: MY_OPTION, useValue: 50}

And finally in your service

constructor(@Inject(MY_OPTION) option: number) {}

For the default option, you can use the @Optional attribute in combination with @Inject

like image 158
Noémi Salaün Avatar answered Oct 29 '25 05:10

Noémi Salaün



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!