Angular 2 - useValue vs useFactory

What is the difference between useValue and useFactory providers?

UseFactory seems to return a value, and useClass also does the same.

+6
source share
2 answers

useValue: will assign the current any assigned instance of the object you provided.

useFactory : It also does the same. You can customize the factory object based on another dependency inside the function and before returning its instance.

 { provide: CustomDependency, useFactory: () => { if (IS_A) { return new A(); } else { return new B(); } } } 

You can use useFactory to customize your dependency during customization. Same as config phase Angular 1, where you modify or form a dependency as needed.

+7
source
  • useFactory takes a factory function, which is expected to return a value, and may also have dependencies (requires instances of other providers to be passed as parameters)

See, for example, the config:ConfigService parameter required by the factory function in How to pass parameters passed from the backend to the angular2 bootstrap method

  • useValue is just a value that is entered as

  • useClass expects the type name and Angular to create an instance from the passed type, and also allow and pass constructor parameters to the class, if any

  • There is also useExisting , which is similar to an alias for an already registered provider. A use case is to provide the same provider instance with different keys.

For an example, see Angular 2 using existing providers .

+6
source

Source: https://habr.com/ru/post/1012529/


All Articles