3 minute read

Let’s have a look at how the switchMap operator may be used in Angular 14 routing. With Activated Route, we can utilize the switchMap operator.

To begin, import the modules Router, ActivatedRoute, and ParamMap from the router package. Then, import the switchMap operator, which will be used later to handle the observable route parameters. As is customary, you’ll write a constructor in which you request that Angular inject services that the component requires and reference them as private variables.

Later, in the ngOnInit method, you’ll use the ActivatedRoute service to retrieve the parameters for the route, pull the employee ID from the parameters, and retrieve the employee to display. The paramMap processing is a bit tricky. When the map changes, you’ll get() the ID parameter from the changed parameters. You might think now is the time to use the RxJS map operator but the EmployeeService operator returns an Observable. So, you flatten the observable with the switchMap operator instead. The switchMap operator also cancels previous in-flight requests. If the user re-navigates to this route with a new ID while the EmployeeService is still retrieving the old ID, switchMap discards the old request and returns the employee for the new ID.

Filename: employe-detail.component.ts

1import { switchMap } from 'rxjs/operators';
2import { Component, OnInit } from '@angular/core';
3import { Router, ActivatedRoute, ParamMap } from '@angular/router';
4import { Observable } from 'rxjs';
6import { EmployeeService }  from '../employee.service';
7import { Employee} from '../employee;
[email protected]({
10  selector: 'app-employee-detail',
11  templateUrl: './employee-detail.component.html',
12  styleUrls: ['./employee-detail.component.css']
14export class EmployeeDetailComponent implements OnInit {
15  employee$: Observable<Hero>;
17  constructor(
18        	private route: ActivatedRoute,
19        	private router: Router,
20        	private service: EmployeeService
21  ) {}
23  ngOnInit() {
24        	this.employee$ = this.route.paramMap.pipe(
25      switchMap((params: ParamMap) =>
26        	this.service.getEmployee(params.get('id')))
27        	);
28  }
29  }

Let’s look at another example of the search functionality of employees. By exploring this example, we will be able to understand the characteristics of the switchMap() operator.

Filename: search.component.html

1<input (keyup)="search($event.target.value)" id="name" placeholder="Search"/>
4  <li *ngFor="let employee of employee$ | async">
5        	<b> v.</b> -
6        	<i></i>
7  </li>

The (keyup) event binding sends every keystroke to the component’s search() method. Sending a request for every keystroke could be expensive. It’s better to wait until the user stops typing and then send a request. That’s easy to implement with RxJS operators, as shown in this excerpt.

Filename: search.component.ts

1withRefresh = false;
2employees$: Observable<NpmEmployeeInfo[]>;
3private searchText$ = new Subject<string>();
5search(employeeName: string) {
6  this.searchText$.next(employeeName);
9ngOnInit() {
10  this.employees$ = this.searchText$.pipe(
11        	debounceTime(500),
12    distinctUntilChanged(),
13        	switchMap(employeeName =>
14      this.searchService.search(employeeName, this.withRefresh))
15  );
18constructor(private searchService: EmployeeSearchService) { }

The searchText$ is the sequence of search-box values coming from the user. It’s defined as an RxJS Subject, which means it is a multicasting observable that can also produce values for itself by calling next(value), as happens in the search() method. Rather than forward every searchText value directly to the injected EmployeeSearchService, the code in ngOnInit() pipes search values through three operators:

  • debounceTime(500) - wait for the user to stop typing (1/2 second in this case).

  • distinctUntilChanged() - wait until the search text changes.

  • switchMap() - send the search request to the service.

The switchMap() operator has three important characteristics.

  • It takes a function argument that returns an observable. EmployeeSearchService.search returns an observable, as other data service methods do.

  • If a previous search request is still in-flight (as when the connection is poor), it cancels that request and sends a new one.

  • It returns service responses in their original request order, even if the server returns them out of order.


In this guide, we have explored how we can use the switchMap operator to transform data in Angular. We have also seen how we can use the switchMap operator along with other operators and pipe functions in our application.