0

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.

3
  • Trying to avoid any opnion based answer, to me this looks fine. Commented May 20, 2022 at 10:50
  • You can share your opinion in a constructive way Commented May 20, 2022 at 10:52
  • 1
    Of course, but there's nothing to say about that. It's the correct way to make an API call in thie case. The async pipe wouldn't really fit this time, since you are saving some data instead of just displaying it. Commented May 20, 2022 at 10:54

1 Answer 1

1

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) => {
      // throw error to observer and treat it in subscription
      return throwError(() => new Error(err));
    })
  );
}
Sign up to request clarification or add additional context in comments.

2 Comments

You dont have to set headers to the call because the documentation doesnt require them.
I was talking about the PokeAPI, but you are 100% right. Thankyou

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.