0
0
Angularframework~5 mins

Creating a service with CLI in Angular

Choose your learning style9 modes available
Introduction

Services help you share data and logic across parts of your app. Using the CLI to create a service saves time and sets it up correctly.

You want to keep your code organized by separating data logic from UI.
You need to share data or functions between multiple components.
You want to use Angular's dependency injection to manage your service.
You want to quickly generate a service file with the right structure.
You want to follow Angular best practices without writing boilerplate code.
Syntax
Angular
ng generate service service-name

# or shorter
ng g s service-name

Replace service-name with your desired service name.

The CLI creates two files: service-name.service.ts and service-name.service.spec.ts for testing.

Examples
This creates a service named UserService in the current folder.
Angular
ng generate service user

# creates user.service.ts and user.service.spec.ts
This creates a service inside a shared folder, organizing your code better.
Angular
ng g s shared/logger

# creates shared/logger.service.ts and shared/logger.service.spec.ts
Sample Program

This example shows how to create a simple GreetingService using the CLI. The service has a method to return a greeting message. The component uses this service to display a message.

Angular
ng generate service greeting

// greeting.service.ts
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class GreetingService {
  sayHello(name: string): string {
    return `Hello, ${name}!`;
  }
}

// Usage in a component
import { Component } from '@angular/core';
import { GreetingService } from './greeting.service';

@Component({
  selector: 'app-root',
  template: `<h1>{{ message }}</h1>`
})
export class AppComponent {
  message = '';
  constructor(private greetingService: GreetingService) {
    this.message = this.greetingService.sayHello('Friend');
  }
}
OutputSuccess
Important Notes

Services created with CLI are automatically injectable and ready to use.

Use providedIn: 'root' to make the service available app-wide without extra setup.

Remember to import the service in components where you want to use it.

Summary

Use Angular CLI to quickly create services with correct structure.

Services help share logic and data across components.

CLI-generated services are ready for dependency injection and testing.