What are providers in Angular2?

后端 未结 5 1959
挽巷
挽巷 2020-12-14 05:58

In the Angular2 component configuration providers is one of the keys that we could specify. How are these providers defined and what are they used for?

5条回答
  •  既然无缘
    2020-12-14 06:43

    Think of providers like a recipe that tells angular how to inject a service.

    We often declare providers in angular this way:

    providers: [AnyService]
    

    This is just a short hand for this:

    [new Provider(AnyService, {useClass: AnyService})]
    

    Both approaches are saying: Whenever someone requires "AnyService", provide the class "AnyService"

    See that even though I'm providing the same class in the example above, in another scenario I could do something like this.

    [new Provider(AnyService, {useClass: AnyServiceCustom})]
    

    But in both scenarios, constructor would remain the same:

    constructor( private _anyService: AnyService) {
    }
    

    To understand it better you need to understand how dependency injection works in Angular 2 as providers are directly related to it.

    This is a must-read for every angular 2 developer.

    https://angular.io/docs/ts/latest/guide/dependency-injection.html?The%20Provider%20class%20and%20provide%20function#!#injector-providers

提交回复
热议问题