What is multi provider in angular2

后端 未结 4 1882
逝去的感伤
逝去的感伤 2020-12-29 18:34

I understand that provider is for getting service from another class but what is multi-provider and token thing?

And also when we do multi=true ?

<
4条回答
  •  自闭症患者
    2020-12-29 19:14

    What is a multi-provider?

    Provider is defined here.

    https://angular.io/api/core/Provider

    Basically, the provider describes how an injector is configured. So a multi-provider is you using multiple providers instead of a single provider, for instance

    providers: [
     { provide: TOKEN1 , useClass: ClassName1},
    
     { provide: TOKEN2 , useClass: ClassName2}
    ]
    

    In the above scenario, instances of both classes are created for the given token. This is then available for dependency injection (In the constructors of the particular classes.)


    What is Token?

    Token is the lookup key for locating the dependency value, for instance let’s take as follows…

    then the lookup key is the TYPE of className, and the dependency value is the INSTANCE of its class.

    providers: [ClassName]
    

    In the following example, the TOKEN1, and TOKEN2 are the lookup keys, and the dependency values are the instance of both classes.

    providers: [
     { provide: TOKEN1 , useClass: ClassName1},
    
     { provide: TOKEN2 , useClass: ClassName2}
    ]
    

    When do we use multi=true ?

    The multi is useful when you register multiple providers for the same token. Let’s say in the following example, then the last provider is injected because it’s used at the end, meaning

    you won’t be able to use a ClassName1 instance. So what you can do is to use multi=true, and this signals Angular to register multiple providers for the SAME token. So this injects an ARRAY of values.

    What is the value? the value is the INSTANCE of the classes.

    providers: [
     { provide: TOKEN , useClass: ClassName1},
    
     { provide: TOKEN , useClass: ClassName2}
    ]
    

    So the rule of thumb is if you are registering multiple providers for the same TOKEN then always use multi=true to avoid the first provider from not injected. When it's injected, you can use it in the constructor of the class.

    NOTE: I am not an expert in this area. So if you saw any problem please let me know.

提交回复
热议问题