Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 894
Mike Bovenlander Avatar asked Oct 07 '16 09:10

Mike Bovenlander


People also ask

What is used to create Angular service in Angular CLI?

By default, the Angular CLI command ng generate service registers a provider with the root injector for your service by including provider metadata in the @Injectable() decorator.

What is service in Angular CLI?

The Angular CLI is a powerful tool that can help automate a variety of tasks. These tasks range from updating your project's Angular version to creating a new Angular component or service. In a real Angular app, the Angular CLI will save you a lot of time by creating app boilerplate for you.


2 Answers

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)
like image 172
Meir Avatar answered Sep 21 '22 19:09

Meir


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.

like image 29
jtinsley85 Avatar answered Sep 21 '22 19:09

jtinsley85