How to use switchMap operator in Angular
The switchMap operator is essential for handling scenarios where you need to cancel previous observable emissions and switch to new ones. As the creator of CoreUI with over 25 years of development experience, I use switchMap extensively for search functionality and dependent HTTP requests. The most common use case is implementing live search where each keystroke should cancel the previous search request. This prevents race conditions and ensures only the latest result is processed.
Use switchMap to cancel previous observables and switch to the latest emission, ideal for search and dependent HTTP calls.
import { Component } from '@angular/core'
import { FormControl } from '@angular/forms'
import { switchMap, debounceTime, distinctUntilChanged } from 'rxjs'
import { SearchService } from './search.service'
@Component({
selector: 'app-search',
template: `
<input [formControl]="searchControl" placeholder="Search users...">
<div *ngFor="let user of users">{{ user.name }}</div>
`
})
export class SearchComponent {
searchControl = new FormControl('')
users: any[] = []
constructor(private searchService: SearchService) {
this.searchControl.valueChanges.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap(query => this.searchService.searchUsers(query))
).subscribe(users => this.users = users)
}
}
This example demonstrates switchMap’s key behavior: when the user types a new character, it automatically cancels the previous HTTP request and starts a new one. The debounceTime(300) waits 300ms after the user stops typing, distinctUntilChanged() only proceeds if the value actually changed, and switchMap handles the HTTP request cancellation and switching.
Best Practice Note:
This pattern is used in CoreUI’s advanced search components to provide responsive, efficient search experiences. Always combine switchMap with debounceTime for user input to avoid excessive API calls.



