Hung Vi
Hung Vi

Reputation: 490

Angular 2 architecture - place for shared services accross modules

I have read about some Angular 2 project architecture, but they are not my case.

My question is where to place shared service that is used across modules.

My project has multiple modules, for example: admin module and user module.

This this the structure:

app |admin | |- some admin components | |- admin.module |user | |- some user components | |- shared | |- user.service | |- user.module

The problem is: I want to retrieve user's information in some components of admin module. So, I import user service into admin module and place it in admin module provider.

I think that this is not a good practice.

I found this: http://jasonwatmore.com/post/2016/08/16/angular-2-jwt-authentication-example-tutorial But I don't know if it is good practice. Should I place user.service to app/_services for common use? Should I create a services.module to initialize user.service, then, import service module to others module?

app |_services | |- user.service |admin | |- some admin components | |- admin.module - import and set user.service to provider |user | |- some user components | |- user.module - import and set user.service to provider `

Upvotes: 3

Views: 2064

Answers (1)

Eeks33
Eeks33

Reputation: 2315

It's fine to import user service into admin components if you need to. It just means that the admin module will be dependent on the user module, which is totally fine, but you may want to put some conscious effort into structuring your dependency trees so they don't get out of hand.

Keep all the user services and user components inside user, don't put user service in a shared services folder. This is the most scaleable architecture. It goes by the name "folder-by-feature" or "single responsibility". If you start a "shared" folder where you just stick in services from all your modules, soon that folder will be huge and all parts of your application will be dependent on that folder, tightly coupling your entire application.

See John Papa's official angular2 style guide that advocates single responsibility: https://angular.io/docs/ts/latest/guide/style-guide.html

Upvotes: 4

Related Questions