Mike Bovenlander
Mike Bovenlander

Reputation: 5426

Angular cli service generation: service is generated in root instead of /services

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.

Upvotes: 25

Views: 39237

Answers (4)

jtinsley85
jtinsley85

Reputation: 61

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.

Upvotes: 5

phil123456
phil123456

Reputation: 1638

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]

Upvotes: 3

Rokive
Rokive

Reputation: 825

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

Upvotes: 0

Meir
Meir

Reputation: 14385

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)

Upvotes: 41

Related Questions