Angular cli generate service

49434 months ago

Published on October 11, 2017
Uploaded By: kudvenkat

In this video we will discuss generating services using the Angular CLI. Generating services is similar to generating components.

To generate a component we use
ng generate component componentName or ng g c componentName

Similarly to generate a service we use
ng generate service serviceName or ng g s serviceName

For example. to generate a customer service we use the following command.
ng generate service customer

The above command generates the service and the spec file. What it does not do is register the service. Remember for us to be able to use the service, we must register the service.

We can do it manually after creating the service or we can tell Angular CLI to register our service with a module, using --module option. We can also use it's alias -m

The following command not only generates employee service, it also registers our service witht the AppModule
ng generate service employee -module=app.module

The above command can also be rewritten using aliases
ng g s employee -m=app.module

We can also use the --dry-run flag or it's alias -d to see what Angular CLI generates. Notice in the following command we are using -d option, so Angular CLI simply report the files it is going to generate
ng g s student -d

The above command generates the service and the spec file. If you do not want the spec file, simply set --spec=false
ng g s student -d --spec=false

When generating a component, Angular CLI by default creates a folder for the component and places all the component files in that folder. A service on the other hand will not have it's own folder. If you want a folder of it's own for a service that the Angular CLI is generating, set --flat option to false as shown below.
ng g s student -d --spec=false --flat=false

Text version of the video


Angular CLI Tutorial

Angular CLI Text articles & Slides

All Dot Net and SQL Server Tutorials in English

All Dot Net and SQL Server Tutorials in Arabic