angular: many components using reusable service

466 Views Asked by At

I'm following todd motto's styleguide for angular. And in his approach, and in john papa's approach as well, they say each component should have its own services in which they depend.

My question is, what happens when I have a service (e.g. getArticlesByStoreId) that I want to use from different components that do not relate to each other. From this styleguides, I would understand that I have to rewrite my service file into both components, but I think I could have a "sharedServices/" for all those shared services so I don't end up rewriting code.

What would you guys do in this case?

app/  
|--components/  
   |--comp1/  
      |--service.js  
   |--comp2/  
      |--service.js  

or

app/  
|--components/  
   |--comp1/  
   |--comp2/  
|--services/  
   |--sharedServices/
      |--service.js
2

There are 2 best solutions below

0
On

I am using Angular 1.5 and component architecture in large scale project. We have the following structure and so far so good.

└─ src/app/ ├─ app.js # app entry file ├─ app.html # app template ├─ common/ ├─ common.js # common entry file └─ services/ # common services └─ components/ # where components live ├─ components.js # components entry file └─ home/ # home component ├─ home.js # home entry file (routes, configurations etc) ├─ home.component.js # home component definition ├─ home.controller.js # home controller ├─ home.service.js # home service ├─ home.scss # home styles ├─ home.html # home template └─ home.spec.js # home specs (for entry, component, and controller)

0
On

Ok Since your question is what would I do, I would do this... structure my app by feature (one of John Papas folder structure). Remember each application may need different folder structure. I use the below folder structure for small to medium apps. Again, your application needs are important here. How much will your app grow and how manageable will it be with the folder structure you will use.

app/  
    |--core
        |--login.service.js
    |--feature1/  
        |--feature1.component.js
        |--feature1.service.js  
    |--feature2/  
        |--feature2.service.js 

I like to have my folder structure as flat as possible. I believe, I read in John Papas guidelines for folder structure to not have more than 2 nested folders. Here is the article where he says it: https://johnpapa.net/angular-app-structuring-guidelines/