0

I'm still fairly new to Angular, and am trying to wrap my brain around something that I hope someone can shed a little light on for me...

I've got a module that has a robust (singleton) service in it that I want some of my other components to be able to access. I've currently got it exporting with the static forRoot(): ModuleWithProviders stuff, and importing into "app.module.ts".

Now, I can get it to work successfully. If, in the component to use the service, I add an import statement like this:

import { XyzService } from '../../modules/xyz/xyz.service';

and inject it into the component's constructor:

constructor(private _xyzr: XyzService) { }

But that seems too tightly coupled. Every single component has to import the module's service? Is that the right way to do this? Is there a better way? Something that would allow me to swap out the module for a newer/better one on down the road without having to go touch every single component...

Thanks!

Rick
  • 245
  • 3
  • 13
  • you are doing it the right way. go through this documentation https://angular.io/guide/dependency-injection-pattern – Vikas Mar 15 '18 at 17:27

1 Answers1

0

You are right, every Component needs to import the corresponding Service to use it.

Unfortunately, as far as I'm aware, there is no "nice" solution to completely change a service later without replacing it's occurrences in the files (luckily this is a fast task due to modern IDEs). If you only optimize your existing Service there is no need to replace anything at all. The one solution I found which might be helpful for you is this.

If you, later on, have a lot of commonly used services it's good practice to create a "shared-module" that you can easily import in other modules (but this will only handle the import mess in modules, not in components).

Alex
  • 1,857
  • 3
  • 36
  • 51
  • Hmm in that case, is it a good idea to use the path mapping stuff in tsconfig to sort of abstract out the exact full path to the service’s .ts file? https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping – Rick Mar 15 '18 at 21:51
  • TBH I'm not sure about this. Never saw such a thing in an angular application. – Alex Mar 15 '18 at 23:15