Creating a Service
Creating a service in Angular is straightforward. You can generate one using the Angular CLI or create it manually. Let's see both approaches.
Method 1: Using Angular CLI (Recommended)
Run this command in your terminal:
ng generate service data
# or shorthand
ng g s data
This creates two files: data.service.ts and data.service.spec.ts (for testing).Method 2: Creating Manually
Create a file
data.service.ts and add:import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
private data: string[] = [];
constructor() {
console.log('DataService created');
}
addItem(item: string) {
this.data.push(item);
}
getItems() {
return this.data;
}
clearItems() {
this.data = [];
}
}
Understanding @Injectable
The
providedIn: 'root' tells Angular to create a single, shared instance of this service throughout the entire application (singleton). This is the most common and recommended way.Service with HTTP calls
Most services will make API calls using HttpClient:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ApiService {
private apiUrl = 'https://jsonplaceholder.typicode.com';
constructor(private http: HttpClient) { }
getPosts(): Observable {
return this.http.get(`${this.apiUrl}/posts`);
}
}
Two Minute Drill
- Use `ng g s service-name` to generate a service.
- @Injectable decorator makes a class injectable.
- `providedIn: 'root'` creates a singleton service.
- Services can hold data, logic, or make HTTP calls.
- Constructor runs once when service is first created.
Need more clarification?
Drop us an email at career@quipoinfotech.com
