Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 providedin doesn't work -> StaticInjectorError

Tags:

angular

I'm trying to use 'providedin' feature in Angular but receive the error "StaticInjectorError(AppModule)[DashboardComponent -> DashboardService]:"

@Injectable({
  providedIn: DashboardModule
})
export class DashboardService {
  getContent() {
    return 'Dashboard Service works!!!';
  }
}

Full demo https://stackblitz.com/edit/angular-kbkjet Thanks for you effort!

like image 610
SIARHEI PAKHUTA Avatar asked Jun 29 '18 08:06

SIARHEI PAKHUTA


1 Answers

  • 98% of the time, use providedIn = 'root'. It will register the service with the root application injector, will be tree shaken, and will be available to any component that needs it. The tree shaking will ensure the service is only included in the bundles where it is used.
  • Use the providers array in a component if the service only needs to be provided in the component and its nested children. (For service isolation at the component level or if you need multiple instances of the service per component.)
  • Don't use the providers array in a module (this is old syntax and it no longer recommended)
  • Use providedIn='lazymodule' if you want to limit access to a service to a particular lazy loaded module. It will then require an additional module to prevent the circular dependency issue. This provides service isolation at the module level. If any other component in the application outside of this lazy loaded module attempts to reference the service an "out of injector scope" error is generated.

See this for more information on the "additional module": https://www.youtube.com/watch?v=jigR_jBhDMs&feature=youtu.be

Sample code here: https://github.com/web-dave/provide-in-test

Discussion of the circular dependency issue here: https://github.com/web-dave/provide-in-test/issues/1

like image 117
DeborahK Avatar answered Nov 09 '22 13:11

DeborahK