Created
August 9, 2019 11:47
-
-
Save saimon24/dfaea56bc4c020040037dd9aedbfb37c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { HttpClient } from '@angular/common/http'; | |
import { map } from 'rxjs/operators'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class PokemonService { | |
baseUrl = 'https://pokeapi.co/api/v2'; | |
imageUrl = 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/'; | |
constructor(private http: HttpClient) {} | |
getPokemon(offset = 0) { | |
return this.http | |
.get(`${this.baseUrl}/pokemon?offset=${offset}&limit=25`) | |
.pipe( | |
map(result => { | |
return result['results']; | |
}), | |
map(pokemon => { | |
return pokemon.map((poke, index) => { | |
poke.image = this.getPokeImage(offset + index + 1); | |
poke.pokeIndex = offset + index + 1; | |
return poke; | |
}); | |
}) | |
); | |
} | |
findPokemon(search) { | |
return this.http.get(`${this.baseUrl}/pokemon/${search}`).pipe( | |
map(pokemon => { | |
pokemon['image'] = this.getPokeImage(pokemon['id']); | |
pokemon['pokeIndex'] = pokemon['id']; | |
return pokemon; | |
}) | |
); | |
} | |
getPokeImage(index) { | |
return `${this.imageUrl}${index}.png`; | |
} | |
getPokeDetails(index) { | |
return this.http.get(`${this.baseUrl}/pokemon/${index}`).pipe( | |
map(poke => { | |
let sprites = Object.keys(poke['sprites']); | |
poke['images'] = sprites | |
.map(spriteKey => poke['sprites'][spriteKey]) | |
.filter(img => img); | |
return poke; | |
}) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment