If you’re building modern web applications with Angular, you’ve probably seen the subscribe() function everywhere in HTTP requests, route parameters, form controls, and more.
But what exactly does subscribe() do, and why is it so essential in Angular development?
In this guide, we’ll explore the subscribe() function in simple terms, learn how it works with Observables, and see how to use it efficiently following Angular best practices.
What Is subscribe() in Angular?
In Angular, many features like HTTP requests, route changes, and form updates rely on Observables.
An Observable is a data stream that can emit multiple values over time. It’s part of RxJS (Reactive Extensions for JavaScript) a library that powers Angular’s reactive features.
However, Observables are lazy. They don’t start sending data until you subscribe to them.
In short:
The subscribe() function listens to an Observable and lets you react when it emits data, errors, or finishes.
⚙️ The Syntax of subscribe()
myObservable.subscribe(
(value) => console.log('Data received:', value), // next
(error) => console.error('Error:', error), // error
() => console.log('Observable completed') // complete
);
Parameters:
- Next → Triggered when the Observable emits data
- Error → Called if something goes wrong
- Complete → Runs when the Observable finishes sending values
Real Example: Using subscribe() with HTTP Requests
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-user-list',
template: `
<h3>User List</h3>
<ul>
<li *ngFor="let user of users">{{ user.name }}</li>
</ul>
`
})
export class UserListComponent implements OnInit {
users: any[] = [];
constructor(private http: HttpClient) {}
ngOnInit() {
this.http.get<any[]>('https://jsonplaceholder.typicode.com/users')
.subscribe({
next: (data) => this.users = data,
error: (err) => console.error('Failed to load users:', err),
complete: () => console.log('Request completed')
});
}
}
Explanation:
- The HttpClient.get() method returns an Observable.
- Using .subscribe() starts the request.
- When data arrives, it’s handled in the
nextcallback.
🧹 Unsubscribing to Avoid Memory Leaks
When you subscribe to long-lived Observables (like interval, valueChanges, or sockets), you must unsubscribe to prevent memory leaks.
Example:
import { Subscription } from 'rxjs';
export class MyComponent implements OnInit, OnDestroy {
private subscription!: Subscription;
ngOnInit() {
this.subscription = this.myService.getData().subscribe(data => {
console.log(data);
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
Best Practice:
Always unsubscribe in ngOnDestroy() if the Observable doesn’t complete automatically.

