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
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?
Use ng generate to create the MessageService in src/app .
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With