Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does multi:true mean in providers in angular4

I am using HTTP_INTERCEPTORS in angular4. For this, I have created HttpServiceInterceptor class that implements HttpInterceptor interface and provide the defintion for intercept method. Then registered provider for HTTP_INTERCEPTORS like this

providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: HttpServiceInterceptor,
    multi: true
}],

and this is working fine. But still I don't understand what does multi:true mean here? I have read this answer.

If I remove multi:true option then there is an error on browser side

Uncaught Error: Provider parse errors:
Mixing multi and non multi provider is not possible for token InjectionToken_HTTP_INTERCEPTORS ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1
    at NgModuleProviderAnalyzer.webpackJsonp.487.NgModuleProviderAnalyzer.parse (vendor.js:36335)
    at NgModuleCompiler.webpackJsonp.487.NgModuleCompiler.compile (vendor.js:43184)
    at JitCompiler.webpackJsonp.487.JitCompiler._compileModule (vendor.js:51527)
    at vendor.js:51472
    at Object.then (vendor.js:26354)
    at JitCompiler.webpackJsonp.487.JitCompiler._compileModuleAndComponents (vendor.js:51470)
    at JitCompiler.webpackJsonp.487.JitCompiler.compileModuleAsync (vendor.js:51399)
    at PlatformRef_.webpackJsonp.0.PlatformRef_._bootstrapModuleWithZone (vendor.js:4746)
    at PlatformRef_.webpackJsonp.0.PlatformRef_.bootstrapModule (vendor.js:4732)
    at Object.<anonymous> (app.js:23366)

Does this mean HTTP_INTERCEPTORS is multi-provider that initializes multiple directives or components? If so then what are other directives and components?

like image 232
Sunil Garg Avatar asked Dec 11 '17 07:12

Sunil Garg


1 Answers

Multi-providers have nothing to do with directives. This answer mentions directives only as an example.

Considering that FOO is injection token, this

providers: [
  { provide: FOO, useClass: Bar, multi: true },
  { provide: FOO, useClass: Baz, multi: true }
]

makes FOO injected dependency an array of multiple providers that were assigned to this token, i.e. is same thing as:

providers: [
  { provide: FOO, useValue: [Bar, Baz] }
]

The difference is that multi-providers can be defined in multiple places on same injector, and all additional { provide: FOO, multi: true, ... } do a push to FOO array.

like image 197
Estus Flask Avatar answered Oct 11 '22 13:10

Estus Flask