Is `providers: [ MyService ]` the same as `providers: [{ provide: MyComponent, useClass: MyComponent }]`

157 Views Asked by At

I'm reading the ng-book on angular 2 revision 47 page 250 and there is the following passage:

When we put the class itself into the list of providers like this:

providers: [ MyService ] 

That is telling Angular that we want to provide a singleton instance of MyService whenever MyService is injected. Because this pattern is so common, the class by itself is shorthand notation for the following, equivalent configuration:

providers: [
    { provide: MyComponent, useClass: MyComponent }
]

Is it a typo and what is meant should be:

providers: [
    { provide: MyService, useClass: MyService }
]
3

There are 3 best solutions below

0
On BEST ANSWER

It's typo, since you can't use components as Providers, here's the official docs

The Provider class and provide object literal We wrote the providers array like this:

providers: [Logger]

This is actually a shorthand expression for a provider registration using a provider object literal with two properties:

[{ provide: Logger, useClass: Logger }]

The first is the token that serves as the key for both locating a dependency value and registering the provider.

The second is a provider definition object, which we can think of as a recipe for creating the dependency value. There are many ways to create dependency values ... and many ways to write a recipe

3
On

Yes, it's the same. When the type passed to provide and useClass is the same, then it's equivalent to just pass the type.

Just a hint. Providing a component (MyComponent) usually doesn't make sense.

0
On

Yes, both of them are same. When you write providers: [MyService] angular will expand this into [{ provide: MyService, useClass: MyService}] where the first parameter provide: MyService will work as a Dependency injection token that will work as a key to locate "MyService" and the second parameter useClass: MyService it will create dependency from the existing service class MyService