Angular 9 Subscribe in Subscribe (Best Practices 1)

In some cases, for example you may need to get userId from httpclient request then use that userId in another client request. Well, if you’re a beginner you will think about to handle it in subscribe in subscribe.

Do not use subscribe in subscribe. Use mergeMap instead.

Here is my model file including Todo and User model.

// models.model.ts

export interface Todo {
    userId: number;
    id: number;
    title: string;
    completed: boolean;
}

export interface User {
    id: number;
    name: string;
    username: string;
    email: string;
    address: {
       street: string;
       suite: string;
       city: string;
       zipcode: string;
       geo: {
           lat: string;
           lng: string;
       }
    };
    phone: string;
    website: string;
    company: {
        name: string;
        catchPhrase: string;
        bs: string;
    };
}

My component which is using mergeMap.

// myapp/myapp.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { mergeMap } from 'rxjs/operators';

import { Todo, User } from '../models.model';

@Component({
selector: 'app-myapp',
templateUrl: './myapp.component.html',
styleUrls: ['./myapp.component.css']
})

export class MyappComponent implements OnInit {

constructor(private http: HttpClient) { }

todo: Todo;
user: User;

ngOnInit(): void {
this.http.get<Todo>('https://jsonplaceholder.typicode.com/todos/1')
.pipe(mergeMap((todo: Todo) => this.http.get<User>(`https://jsonplaceholder.typicode.com/users/${todo.userId}`))
)
.subscribe((user: User) => this.user = user);
}
}
    {{ user.id }}
    {{ user.name }}
    {{ user.username }}
    {{ user.email }}
    {{ user.address.city }}
    {{ user.address.geo.lat }}