Angular is a TypeScript-based open-source web application framework developed by the Angular Team at Google, along with contributions from a vibrant community of individuals and corporations. It is a complete rewrite of AngularJS, built by the same team.
In this article, we will explore the switchMap operator in Angular, which is one of the most commonly used operators from the RxJS library. We’ll delve into its functionality, understand how it works within an Angular application, and provide a live example to demonstrate its usage.
By the end of this post, you will gain familiarity with the following topics:
- Understanding RxJS: What exactly is RxJS and how do its operators work in an Angular application?
- Exploring the switchMap Operator: What is the switchMap operator and how does it enhance the functionality of Angular applications? We will also provide a live example to demonstrate its usage.
- Handling Multiple Requests: Learn how to effectively handle multiple requests using the switchMap operator…
switchMap operator
The switchMap
operator is a powerful flattening operator that works with two observables
: an outer observable and an inner observable. It emits values only from the most recently projected inner observable.
Let’s delve into this operator using a real-world example. Imagine you want to load a post from a web server and, once the post is loaded, download all the related comments. Take a look at the following animation to understand how the switchMap operator functions.
For the purpose of this demonstration, we’ll be using StackBlitz IDE.
Creating a Service to Load Posts and Comments To begin, let’s create a service that will handle the loading of posts and comments.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { of } from 'rxjs';
@Injectable()
export class PostService {
apiURL: string = 'https://jsonplaceholder.typicode.com/posts/1';
constructor(private httpClient: HttpClient) {}
getSinglePost() {
return this.httpClient.get(`${this.apiURL}`);
}
getAllComments(postId: number) {
return this.httpClient.get(`${this.apiURL}/comments`);
}
}$ads={1}
Adding the switchMap Operator in the Angular Component Next, open the app.component.ts
file and add the following code:
import { Component, OnInit } from '@angular/core';
import { switchMap } from 'rxjs/operators';
import 'rxjs/add/observable/from';
import { PostService } from './postservice.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
items;
constructor(private postService: PostService) {}
ngOnInit() {}
ngAfterViewInit() {
// Load Single Post
this.postService
.getSinglePost()
.pipe(
// Switch to load comments
switchMap((res1: any) => this.postService.getAllComments(res1.id))
)
.subscribe(result => {
// Finally get the result and show to page
this.items = result;
console.log(result);
});
}
}
The code is quite straightforward, with the key element being the usage of the switchMap
operator to load the comments.
.getSinglePost()
.pipe(
// Switch to load comments
switchMap((res1: any) => this.postService.getAllComments(res1.id))
)
.subscribe(result => {
// Finally get the result and show to page
this.items = result;
console.log(result);
});
In this code snippet, we retrieve a single post using the getSinglePost()
method and then use the switchMap operator to switch to the getAllComments()
method, passing the post ID as a parameter. Finally, we subscribe to the resulting observable and assign the retrieved comments to the items
variable.
By implementing the switchMap
operator, we can efficiently handle asynchronous operations and optimize the data flow within our Angular application.