angularangular2-injection

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


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 }
]

Solution

  • 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