0

We have a mono repo and using Nx layout with /libs.

A lot of the ....service.ts (services) can be reused in multiple places. Here is the question...

These services are mostly fetches from the REST API and therefore designed to be stay singletons. Where should they be provided?

My thoughts right now is to wrap each service in an NgModule and provide it there. Then, whatever other module wants to use that service will have to import the NgModule.

That way, if multiple modules import it, the NgModule with the service will only get evaluated once and the service it provides will not get re-instantiated.

On the other hand, this would make for quite an explosion in the number of files in my source tree. Is that all worth it or is there a better/more elegant way of accomplishing that?

user1902183
  • 3,203
  • 9
  • 31
  • 48

1 Answers1

2

What I do in our monorepo is create an angular lib

ng g lib --tags="type:data-access" user/data-access

then remove the default module created, because it's not needed.

then create a service

ng g s --project=user-data-access User

this will add the

@Injectable({ providedIn: 'root' })

which will make it a singleton in the app, and provide it in the root app module.

then make sure the service is exported in the index.ts file

Leon Radley
  • 7,596
  • 5
  • 35
  • 54