Template for configuration via DI

I look at the in-memory-web-api implementation and the following code appears:

@Injectable() export class InMemoryBackendService { protected config: InMemoryBackendConfigArgs = new InMemoryBackendConfig(); ^^^^^^ ... constructor( @Inject(InMemoryBackendConfig) @Optional() config: InMemoryBackendConfigArgs ^^^^^^ ) { ... 

As I understand it, the template is as follows:

  • Defined class property and dependency creation without using DI
  • Optional Dependency

If the user provides the changed dependency via DI, it will be entered, and the default instance without DI will be overridden. I suspect something similar, possibly with RequestOptions in the HTTP module.

Is this a common template?

EDIT

It turns out that in-memory-web-api is not the template I'm asking about. Suppose I have a class A that uses an instance of class B for injection with token B Therefore, they are both registered using the root injector:

providers: [A, B]

Now, if the user wants to configure B , he can register the customized version under the same token, thereby effectively overloading the original B :

 providers: [{provide:B, useClass: extendedB}]` 

This is how RequestOptions can be extended in the HTTP module.

0
angular
source share
1 answer

The default value is not just overridden. the most important part here

 Object.assign(this.config, config || {}) 

Nothing will happen without him.

This template does not apply to DI; it is a common recipe for default property values, similar to _.defaults .

I would say that the InMemoryBackendConfig default implementation is a useless abstraction here. Since this.config always merges with config , the former may be a simple object

  protected config: InMemoryBackendConfigArgs = { ... }; 

InMemoryBackendConfig and RequestOptions use complex variations of this template. Yes, in most basic forms this can be done:

 providers: [{provide:B, useClass: extendedB}]` 

This template is widely used by constant services in AngularJS for configuration objects, but the presence of B as a class instead of a simple object allows you to extend the original values โ€‹โ€‹instead of replacing them.

+2
source share

All Articles