Search code examples
angularrxjsrxjs-pipeable-operators

How to send multiple Http request using single Observable


I am trying to create an angular app which can send multiple HTTP requests, based on the options selected by a user from a drop-down, using observables. I checked online but wasn't able to understand the concepts fully. I am not able to use switchMap operator in order to achieve my goals.

Can anyone please have a look and point out my error.

Any suggestions/help would be appreciated.

Thanks.

.component.ts file:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Location } from '@angular/common';

// Router Module for Application level Route
import { Router, ActivatedRoute } from '@angular/router';

//importing route code
import { CountryLanguageService } from '../country-language.service';
import { CountryLanguageHttpService } from '../country-language-http.service';


//importing observables related code
import { Observable, pipe } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { tap } from 'rxjs/operators';
import { delay } from 'rxjs/operators';
import { switchMap } from 'rxjs/operators';


@Component({
  selector: 'app-language',
  templateUrl: './language.component.html',
  styleUrls: ['./language.component.css']
})
export class LanguageComponent implements OnInit, OnDestroy {

  public allSameLanguagesCountries;
  public selectedCode;

  constructor(private countryLanguageHttpService: CountryLanguageHttpService, private _route: ActivatedRoute, private location: Location) {

    console.log("Languages Component Called");
  }

  backClicked() {
    this.location.back();
  }


  ngOnInit() {

    // method to get all same language speaking countries

    this._route.params
    .pipe(switchMap(params => this.selectedCode = params['code']));
    console.log(this.selectedCode);
    this.allSameLanguagesCountries = this.countryLanguageHttpService.getAllSameLanguagesCountries(this.selectedCode)
      .subscribe(
        data => {
          console.log(data);
          this.allSameLanguagesCountries = data;

        },
        error => {
          console.log("Some Error Occurred");
          console.log(error.errorMessage);
        }
      )
  }

  ngOnDestroy() {
    console.log("Language Component Destroyed");
  }
}

.http-service.ts file:

import { Injectable } from '@angular/core';

//importing Http Client to make the request
import { HttpClient, HttpErrorResponse } from '@angular/common/http';

// Router Module for Application level Route
import { Router, ActivatedRoute } from '@angular/router';

//importing observables related code
import { Observable, pipe } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { tap } from 'rxjs/operators';
import { delay } from 'rxjs/operators';
import { switchMap } from 'rxjs/operators';


@Injectable({
  providedIn: 'root'
})


export class CountryLanguageHttpService {

  public currentLanguageCode;

  public baseUrl = 'https://restcountries.eu/rest/v2/lang/';

  constructor(private _http: HttpClient) { 
    console.log("Country Language View Service Called");

  }

  // Exception Handler
  private handleError(err: HttpErrorResponse) {
    console.log("Handle error Http calls")
    console.log(err.message);
    return Observable.throw(err.message);
  }


  // method to return single country Informations
  public getAllSameLanguagesCountries(currentLanguageCode): any {

    let myResponse = this._http.get(this.baseUrl + currentLanguageCode);
    console.log(myResponse);
    return myResponse;
  } // end get country info function
}

This is the error I am getting in console.


Solution

  • switchMap change an observable to another. See

    ngOnInit() {
        this._route.params
          .pipe(switchMap(params => 
            {
               //We don't want return the params
               this.selectedCode = params['code']);
               //we want return the countries
               return this.countryLanguageHttpService.getAllSameLanguagesCountries(this.selectedCode)
            }))
          .subscribe(
            data => {
              console.log(data);
              this.allSameLanguagesCountries = data;
            },
            error => {
              console.log("Some Error Occurred");
              console.log(error.errorMessage);
            })
      }