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

Issue

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.

pokemon.service.ts

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

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

@Injectable({
  providedIn: 'root'
})
export class PokemonService {

  constructor(private http: HttpClient) { }

  getRandomPokemon(id: number) {
    return this.http.get(`https://pokeapi.co/api/v2/pokemon/${id}`);
  }
}

app.component.html

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

app.component.ts

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

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

  constructor(private pokemonService: PokemonService) { }

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

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

Solution

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>(`https://pokeapi.co/api/v2/pokemon/${id}`, { headers: headers, observe: "response" })
   .pipe(
    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.