Angular Observables
Learn how Angular uses Observables to work with asynchronous data, events, HTTP responses and continuous data streams.
What is an Observable?
An Observable represents a stream of values that can arrive over time.
Instead of receiving only one value immediately, an Observable can emit multiple values during its lifetime.
Angular applications commonly use Observables for HTTP requests, user events, asynchronous operations and communication between different parts of an application.
Observable Flow
Main Observable Concepts
Observable
Represents a sequence of values over time.
Subscribe
Starts listening to values emitted by an Observable.
next
Handles values emitted by the Observable.
complete
Runs when the Observable finishes emitting values.
Observables and RxJS
Angular commonly works with Observables through RxJS, a library for reactive programming using Observables and operators.
RxJS provides the tools used to create, transform, combine and subscribe to Observable streams.
import { Observable }
from '@rxjs';
Creating a Simple Observable
An Observable can be created using the Observable class.
The subscriber receives values through the next() method.
import { Observable }
from '@rxjs';
const numbers$ =
new Observable<number>(subscriber => {
subscriber.next(10);
subscriber.next(20);
subscriber.next(30);
});
Subscribing to an Observable
To receive values emitted by an Observable, a component or service can subscribe to it.
The subscription receives each value when it is emitted.
numbers$.subscribe({
next: value => {
console.log(value);
},
complete: () => {
console.log('Completed');
}
});
Observable as a Data Stream
Data Stream
Value 1: 10
Value 2: 20
Value 3: 30
Handling next Values
The next callback receives each value emitted by the Observable.
This is where the application can update its state, display data or perform another operation.
data$.subscribe({
next: value => {
console.log(
'Received:',
value
);
}
});
Handling Observable Errors
An Observable can also report an error.
The error callback can be used to handle an error emitted by the Observable.
data$.subscribe({
next: value => {
console.log(value);
},
error: error => {
console.error(
'Error:',
error
);
}
});
Handling complete
The complete callback runs when the Observable finishes successfully.
It is useful when the application needs to perform some action after the stream has ended.
data$.subscribe({
next: value => {
console.log(value);
},
complete: () => {
console.log(
'Observable completed'
);
}
});
CIIT Training Institute Example
Suppose the CIIT Training Institute website receives a stream of course enquiry updates.
An Observable can represent this stream and a component can subscribe to receive each new enquiry.
import { Observable }
from '@rxjs';
const enquiry$ =
new Observable<string>(subscriber => {
subscriber.next(
'New Java Full Stack enquiry'
);
subscriber.next(
'New .NET Full Stack enquiry'
);
subscriber.next(
'New Python Full Stack enquiry'
);
});
enquiry$.subscribe({
next: enquiry => {
console.log(
enquiry
);
}
});
CIIT Training Institute
New Java Full Stack enquiry
New .NET Full Stack enquiry
New Python Full Stack enquiry
Observables with HttpClient
Angular's HttpClient commonly returns Observables for HTTP operations.
A component or service can subscribe to the returned Observable to receive the response.
getCourses() {
return this.http.get<Course[]>(
'/api/courses'
);
}
this.courseService
.getCourses()
.subscribe({
next: courses => {
console.log(courses);
},
error: error => {
console.error(error);
}
});
Observable vs Normal Value
| Feature | Normal Value | Observable |
|---|---|---|
| Values | Usually one current value | Can emit values over time |
| Asynchronous Work | Not designed specifically for streams | Commonly used for asynchronous streams |
| Subscription | Not required | Commonly consumed through subscription |
| Multiple Values | Not represented as a stream | Can emit multiple values |
| RxJS Operators | Not applicable | Can be used to transform streams |
Observable Lifecycle
Create
An Observable is created or obtained from a source.
Subscribe
A consumer subscribes to receive emitted values.
Emit
The Observable emits zero or more values.
Complete / Error
The stream can complete or report an error.
Observable Execution
An Observable describes how a stream of values can be produced and consumed.
The behavior of a particular Observable depends on how it is created and what source it represents.
What is a Subscription?
A Subscription represents an active execution of an Observable.
A subscription can also be used to stop that execution when it is no longer needed.
const subscription =
data$.subscribe({
next: value => {
console.log(value);
}
});
Common Uses of Observables
HTTP
Handle asynchronous HTTP responses.
Events
Represent values from event-based sources.
Data Streams
Work with values arriving continuously over time.
Reactive Logic
Transform and combine asynchronous data streams.
Important Points
An Observable can emit values over time rather than representing only one immediate value.
A consumer generally subscribes to an Observable to receive its emitted values.
Use the error callback when the Observable reports an error.
Long-lived subscriptions should be managed carefully so they do not remain active unnecessarily.
Observable Best Practices
- Understand whether the Observable emits one value or multiple values over time.
-
Handle the
next,errorandcompletecallbacks when appropriate. - Keep data-stream transformations separate from UI-specific logic where practical.
- Manage long-lived subscriptions carefully.
- Use RxJS operators when data needs to be transformed, filtered or combined.
- Avoid unnecessary subscriptions when Angular template features can manage the stream for the required scenario.
Summary
An Observable represents a stream of values that can be emitted over time.
In Angular applications, Observables are commonly used for asynchronous data such as HTTP responses and event-based streams.
Important concepts include Observable, Subscription, next, error and complete. In the next topic, we will learn about Subscription.