Is there a better way to fetch an API on Angular?


Yesterday I was working on a project because I am learning Angular by myself. I tried to make an API call to PokeAPI because I wanted to fetch the .svg for a Pokemon and its name. I made it work, but I do not really know if this can be improved and make something better.

I am providing all the code (since it is a very little program) and a Stackblitz example for testing purposes.


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

import { HttpClient } from '@angular/common/http';

  providedIn: 'root'
export class PokemonService {

  constructor(private http: HttpClient) { }

  getRandomPokemon(id: number) {
    return this.http.get(`${id}`);


<img src="{{ image }}" width="300" height="300">
  {{ actualPokemon }}


import { Component } from '@angular/core';
import { PokemonService } from './services/pokemon.service';

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  title = 'RandomPokemon';
  actualPokemon = '';
  image = '';

  constructor(private pokemonService: PokemonService) { }

  ngOnInit(): void {
    // console.log(this.actualPokemon);
  getRandomPokemon() {
    this.pokemonService.getRandomPokemon(Math.floor(Math.random() * 807) + 1).subscribe(
      (data: any) => {
        this.actualPokemon =;
        this.image = data.sprites.other.dream_world.front_default;
      error => {

I have imported HttpClientModule in app.module.ts but I will not paste it here because it is just a dependency.


Well that is a very general http request, if any error is fired from your side, you won’t even understand why it is failing. I Do not recommend making this kind of request to backend. You want to control data as much as possible

  • no response type specified
  • no observe: response specified
  • no response serializer
  • no interface for response data
  • no error handling

It has absolutely nothing, its just a plain request.

somewhat decent request would look like

getRandomPokemon(id: number): Observable<Pokemon> {
   const headers = new HttpHeaders().set('content-type', 'application/json');

   return this.http.get<Pokemon>(`${id}`, { headers: headers, observe: "response" })
    catchError((err) => {
      // treat error to observer and treat it in subscription
      return throwError(() => new Error(err));

Answered By – tony

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.