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.