Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 629
Pablo Ezequiel Inchausti Avatar asked Mar 12 '17 14:03

Pablo Ezequiel Inchausti


People also ask

What is the Angular CLI command to create service?

Use ng generate to create the MessageService in src/app .

What is service TS in Angular?

Services in Angular are simply typescript classes with the @injectible decorator. This decorator tells angular that the class is a service and can be injected into components that need that service. They can also inject other services as dependencies.


2 Answers

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

like image 169
delasteve Avatar answered Oct 23 '22 11:10

delasteve


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.

like image 39
Simon_Weaver Avatar answered Oct 23 '22 10:10

Simon_Weaver