[javascript] Angular cli generate a service and include the provider in one step

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?

This question is related to javascript typescript angular-cli

The answer is


In Command prompt go to project folder and execute following:

ng g s servicename

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.


In Angular 5.12 and latest Angular CLI, do

ng generate service my-service -m app.module

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

run the below code in Terminal

makesure You are inside your project folder in terminal

ng g s servicename --module=app.module

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

ng g service backendApi --module=app.module

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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to angular-cli

Why powershell does not run Angular commands? ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead Angular CLI Error: The serve command requires to be run in an Angular project, but a project definition could not be found Could not find module "@angular-devkit/build-angular" How to remove package using Angular CLI? How to set environment via `ng serve` in Angular 6 Error: Local workspace file ('angular.json') could not be found How do I deal with installing peer dependencies in Angular CLI? How to iterate using ngFor loop Map containing key as string and values as map iteration how to format date in Component of angular 5