Search code examples
angulartypescriptdirectory-structurefile-structure

Can I placed the reusable component's service in core module in Angular according to the mentioned scenario


├── src
│ ├── app
│ │ ├── core
│ │ │ ├── services
│ │ │ ├── core.module.ts
│ │ ├── shared
│ │ │ ├── produt-form
│ │ │ │ ├── product-form.component.ts|html|css
│ │ │ │ ├── product-form.service.ts
│ │ │ │
I have 2 modules core and shared. I have product-form component in shared module. and also that product-form has product-form.service. I use that service to format the form data and return it again to the product-form.component. that service only use by product-form.
so I need to know, can I placed the product-form.service in product-form component like above structure? or should I placed it in core module services folder?

I am a beginner for angular.

thank you.


Solution

  • Yes, you can. There are few approached in design:

    1. Keep all services separate.
    2. Keep dedicated service in scope of component.
    src
     |-app
     |  |-core
     |     |-services
     |-shared
     |  |-components
     |  |  |-my-component
     |  |    |-my-component.component.html
     |  |    |-my-component.compoennt.ts
     |  |    |-my-component.service.ts
    

    But if you will ask me how I would do, I will create a library and place there all my shared servies and components. In this case they will bake separately in library and the main application will call only what it's needed.

    projects
     |-my-library
     |  |-src
     |  |  |-lib
     |  |     |-components
     |  |     | |-my-component.component.html
     |  |     | |-my-component.component.ts
     |  |     |-services
     |  |     | |-my-component.service.ts
    src
     |-app
     |  |-core
     |  |  |-services
     | ...
    

    If you want to read more about libraries: https://angular.io/guide/creating-libraries