3

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 `

Hung Vi
  • 490
  • 4
  • 16
  • Create another module... something like `SharedModule` then put the *shared* components/services/classes there. To use it, you just need to import the module inside `UserModule` and also `AdminModule`. – developer033 May 10 '17 at 03:29
  • NgModule is such a poorly designed, unnecessary, and confusing abstraction – Aluan Haddad May 10 '17 at 03:57
  • @developer033 as Eeks33 said; in this case, all my modules are tightly coupling with `SharedModule`. I have a `SharedModule` too, but, it's used for another purpose. My `SharedModule` contains some common components, directives, classes, such as form-group, paging, tree-view ... that are reused in multiple modules. Thank for your suggestion. – Hung Vi May 10 '17 at 04:42

1 Answers1

4

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

Eeks33
  • 2,245
  • 1
  • 14
  • 17