24

I'm messing around with Angular a bit. Trying to generate some stuff with angular-cli. But when generating a new service the service is placed in "/src/" folder.

I would like to set a global default folder for this. Is there a config setting where I can do something like: { servicesDir: "/src/services/" }?

I'm using ng generate service Test as command.

Mike Bovenlander
  • 5,236
  • 5
  • 28
  • 47

4 Answers4

38

the cli can take a directory, which in the latest release is also a module, hence use:

ng generate service services/Test

Following the comment below, you might need to first run:

ng generate module services

or

mkdir src/services (or src/app/services, depending on your file structure)
Meir
  • 14,081
  • 4
  • 39
  • 47
  • That gives an error: Invalid path: "C:\......\src\app\services"" is not a valid path. – Mike Bovenlander Oct 07 '16 at 10:00
  • You can do one of the following: 1) ng generate module services 2) mkdir src/app/services (for you it might be mkdir src/services). The first approach is better but fits only the latest cli release. – Meir Oct 07 '16 at 10:04
4

I know this post is a little older but the answers on here still require you to remember to pass your generation command with the specific path. However, it appears the actual request was to set some sort of pre-set or pre-defined path so that all services are generated in the desired path by default.

This is possible by modifying the desired @schematics object within the angular.json file located in the root of your application. Specifically, regarding this request you would make the following modification:

"@schematics/angular:service": {
      "path": "src/services"
    }

This is located under "projects" > [app name] > "schematics". Once you make this change, you simply need to run:

ng g s service-name

and it will create your service in the desired folder.

Note: I'm currently running Angular/Angular CLI version 10.2.0. Though I've used this method in previous versions of Angular as well, but if you're running a much older version this feature may/may not exist.

Dharman
  • 30,962
  • 25
  • 85
  • 135
jtinsley85
  • 51
  • 3
2

ng generates services from src/app, so don't add it to your path when invocating ng

correct usage is (from your project root path, where angular.json is):

ng generate service [path to your component]/[service name]

phil123456
  • 1,192
  • 2
  • 10
  • 26
0

Follow the below steps to generate service using the command line.

  1. Go to services folder cd src/services

  2. To generate service,

ng generate service serviceName

or short

ng g s serviceNam

deepak
  • 1,081
  • 12
  • 18
Rokive
  • 745
  • 9
  • 7