Search code examples
angularjsangularservicedirectory-structure

Where do i create or generate a Service?


I would like to know where should I be generating an angular2 service? The latest documentation of angular2 says its okay to generate a service inside the app folder, however, some video tutorials that I'm following has a shared folder pre-generated in which services are created. I could obviously create that folder but I'd like to know what's appropriate and why?

app-name/src/app/service-name.service.ts

OR

app-name/src/app/shared/service-name.service.ts


Solution

  • i am assuming that you are using Angular-cli folder structure. if you are not using Angular-cli than please do use it.

    suppose you have Component A and Component B.

    Component A: want to use service S1.

    Component B: want to use service S2.

    in that case you create S1 service in Component A folder, and S2 in Component B folder.

    now assume that Component A and Component B want to user Service S3. in this case you should create Service in shared folder.

    summary: if you create service which is used by most of the component of your app, than you should create in shared folder. or 1 component using 1 service that you should create service in that particular component folder.