Which command is used to add a new service in Angular using the CLI?
ng generate service my-new-service

Understanding the Angular CLI Command to Generate a Service

In Angular, a Service is a class with a specific purpose. It can be used anywhere in the application, such as for fetching data from an API, logging data, or any other business logic. This is part of Angular's philosophy to separate concerns and ensure each component does one job well.

The Angular CLI (Comman Line Interface) is a robust tool that allows developers to create, manage, build, and test Angular applications directly from a command shell. One of its commands is to generate a service.

As per the quiz question, the correct command is ng generate service my-new-service. This command is used to create a new service using Angular CLI. Here, my-new-service is the name of the service, which can be changed to whatever you wish to name your service.

Let's break down this command:

  • ng is the Angular CLI command.
  • generate or g for short is used to generate new files or templates in the Angular project.
  • service signifies that we are creating a new service.
  • my-new-service is the name of our new service.

After executing this command, Angular CLI will create a file my-new-service.service.ts in the app folder (by default). The service's skeleton looks like this:

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

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

  constructor() { }

}

You can now inject this service into any component or another service using Angular's DI (Dependency Injection) system.

As a best practice, it's recommended to keep the service name descriptive, reflecting the job it does. Also, creating a separate folder to manage all services can make your codebase much more organized and maintainable.

Thus, the answer to the quiz question: 'Which command is used to add a new service in Angular using the CLI?' is ng generate service my-new-service, which is indeed true.

Do you find this helpful?