76

It is possible generate a service with angular cli and add it as a provider in the app.module.ts in a single step or using an special option in the ng g service command?

When a execute:

$ ng g service services/backendApi
installing service
  create src/app/services/backend-api.service.spec.ts
  create src/app/services/backend-api.service.ts
  WARNING Service is generated but not provided, it must be provided to be used

WARNING Service is generated but not provided, it must be provided to be used

Next to it, (and according to the WARNING message) I usually add it to provider section on app.module.ts using the text editor:

@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  imports: [
    ....
  ],
  providers: [BackendApiService],
  bootstrap: [AppComponent]
})

It is possible to do it with a single step, to automatize this?

Zameer Ansari
  • 28,977
  • 24
  • 140
  • 219
Pablo Ezequiel Inchausti
  • 16,623
  • 7
  • 28
  • 42

10 Answers10

118

Actually, it is possible to provide the service (or guard, since that also needs to be provided) when creating the service.

The command is the following...

ng g s services/backendApi --module=app.module

Edit

It is possible to provide to a feature module, as well, you must give it the path to the module you would like.

ng g s services/backendApi --module=services/services.module

delasteve
  • 2,637
  • 2
  • 17
  • 10
  • Is there a way to provide it in multiple places as well? – Spurious May 16 '17 at 13:17
  • Generally, it's bad practice to provide a service in more than one module. That said, the CLI doesn't allow this with the `--module` flag. You could do it yourself, however, but I'd recommend providing it at a higher level in your application. – delasteve May 17 '17 at 11:24
  • Is enough with `ng g s services/userlist --module=app` – ValRob Apr 04 '18 at 17:24
  • Correct. It's part of the feature I added way back when. `app`, `app.module`, and `app.module.ts` all work. If it contains a path prefix, you can just do `path/to/app` (with all the variations mentioned). Original: https://github.com/angular/angular-cli/commit/314167325486ffc466326fa015d769aed9555c0b#diff-fd1947ec7dd20fca42dd3b6d66fc1b89 Move to Devkit (with updates): https://github.com/angular/devkit/blob/master/packages/schematics/angular/utility/find-module.ts – delasteve Apr 04 '18 at 17:30
  • 25
    The --module flag has been dropped from `$ ng g s` as of Angular 6. See https://github.com/angular/angular-cli/wiki/generate-service and also Simon_Weaver's answer. – SuttonY Jul 01 '18 at 16:33
  • 4
    The answer is incorrect for angular 6 at least. Check @StuttonY's comment. – Ron Jul 20 '18 at 19:59
  • I did the exact thing you said and it returns me this error ` Data path "" should NOT have additional properties(module).` I'm using Angular 6 – Vala Khosravi Aug 15 '18 at 13:23
  • 2
    Adding provider to module doesn't work with angular 6.Service creation using Angular CLI will just generate the service will not be provided, it must be provided to be used. – Vinutha Kumar Oct 04 '18 at 09:33
  • '--module' option is still available for 'component' and 'directive', but as far as I can see not for service anymore. c.f. https://angular.io/cli/generate – Hubert Schumacher Sep 03 '19 at 08:58
  • 1
    Explanation on the removal [SuttonY mentions](https://stackoverflow.com/questions/42748773#comment89235115_42763164) is on the [Angular CLI github Issues page here](https://github.com/angular/angular-cli/issues/11079#issuecomment-397293382). "_Closing this as since Angular version 6 the preferred way to create a services is to specify on the service that it should be provided in the application root. This is done by setting `providedIn` to root on the service's `@Injectable` decorator. With this approach the module is redundant since the the service never gets registered in the `ngModule`._" – ruffin Jun 05 '20 at 14:39
64

Angular 6+ Singleton Services

The recommended approach for a singleton service for Angular 6 and beyond is :

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class UserService {
}

In fact the CLI --module switch doesn't even exist any more for registering a service at the app level because it doesn't need to modify app.module.ts anymore.

This will create the above code, without needing to specify a module.

ng g s services/user

So if you don't want your service to be a singleton you must remove the providedIn code yourself - and then add it manually to providers for a component or lazy loaded module. Doesn't look like there is currently a switch to not generate the providedIn: 'root' part so you need to manually remove it.

Community
  • 1
  • 1
Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
3

Looks like in Angular v11 and higher, we don't have option "s" anymore:

ng g service services/backendApi

or like that:

ng g service services/backendApi --flat --skipTests=true
sam sergiy klok
  • 526
  • 7
  • 17
2

Specify paths

--app
  --one
    one.module.ts
    --services

  --two
    two.module.ts
    --services

Create Service with new folder in module ONE

ng g service one/services/myNewServiceFolderName/serviceOne --module one/one

--one
  one.module.ts // service imported and added to providers.
  --services
    --myNewServiceFolderName
      serviceOne.service.ts
      serviceOne.service.spec.ts
SoEzPz
  • 14,958
  • 8
  • 61
  • 64
2

slight change in syntax from the accepted answer for Angular 5 and angular-cli 1.7.0

ng g service backendApi --module=app.module
user2180794
  • 1,425
  • 7
  • 27
  • 50
  • I just checked with a test project, and my answer still works. Is there something I'm missing? The only difference I can tell is you will generate a service in app/ vs mine which generates in app/services (where @Pablo Ezequiel asked). – delasteve Mar 31 '18 at 12:06
1

Add a service to the Angular 4 app using Angular CLI

An Angular 2 service is simply a javascript function along with it's associated properties and methods, that can be included (via dependency injection) into Angular 2 components.

To add a new Angular 4 service to the app, use the command ng g service serviceName. On creation of the service, the Angular CLI shows an error:

WARNING Service is generated but not provided, it must be provided to be used

To solve this, we need to provide the service reference to the src\app\app.module.ts inside providers input of @NgModule method.

Initially, the default code in the service is:


import { Injectable } from '@angular/core';

@Injectable()
export class ServiceNameService {

  constructor() { }

}

A service has to have a few public methods.

Zameer Ansari
  • 28,977
  • 24
  • 140
  • 219
1

In Angular 5.12 and latest Angular CLI, do

ng generate service my-service -m app.module
Arielle Nguyen
  • 2,932
  • 1
  • 20
  • 15
1
ng generate service userService

//shorthand for creating service
ng g s serviceName

** When you fire this command it will automatically registered inside providers array. **

providers: [
    UserService
]
-1

In Command prompt go to project folder and execute following:

ng g s servicename
Owen Kelvin
  • 14,054
  • 10
  • 41
  • 74
-1

run the below code in Terminal

makesure You are inside your project folder in terminal

ng g s servicename --module=app.module
Asifali
  • 207
  • 3
  • 10