Key Points
- When working with observables, be sure to
subscribe().
- Rather than storing the server response in a local variable, prefer to return the data so that the caller that subscribes to the Observable can decide how to process the data. This has the advantage that as soon as the asynchronous process completes, the data is immediately available.
See working Stackblitz Demo.
Notes on the StackBlitz Demo
- Created an Angular Service
PokeAPIService that calls the PokeAPI server in the constructor.
constructor(private http: HttpClient) {
this.getListOfPokemonUrls().subscribe(
(results: Array<Pokemon>) => {
for(let p of results) {
this.pokemons.push(p)
}
}
)
}
Note that the updated implementation of getListOfPokemonURLs returns the results so that they can be processed within the call to subscribe().
- Defined interfaces for
Pokemon and PokeAPIResponse:
export interface Pokemon {
name: string,
url: string
}
interface PokeAPIResponse {
count: number,
next: string,
previous: string,
results: Array<Pokemon>
}
- Updated
getListOfPokemonUrls() with new interface types and modified RxJS map so that response.results is returned directly.
private getListOfPokemonUrls(): Observable<Array<Pokemon>> {
return this.http.get<any>(POKEAPI_URL)
.pipe(
map((response: PokeAPIResponse) => response.results)
);
}
For reference, the PokeAPI server response:
curl https://pokeapi.co/api/v2/pokemon/
Returns the following response:
{
"count":1050,
"next":"https://pokeapi.co/api/v2/pokemon/?offset=20&limit=20",
"previous":null,
"results":[
{"name":"bulbasaur","url":"https://pokeapi.co/api/v2/pokemon/1/"},
{"name":"ivysaur","url":"https://pokeapi.co/api/v2/pokemon/2/"},
{"name":"venusaur","url":"https://pokeapi.co/api/v2/pokemon/3/"},
{"name":"charmander","url":"https://pokeapi.co/api/v2/pokemon/4/"},
{"name":"charmeleon","url":"https://pokeapi.co/api/v2/pokemon/5/"},
{"name":"charizard","url":"https://pokeapi.co/api/v2/pokemon/6/"},
{"name":"squirtle","url":"https://pokeapi.co/api/v2/pokemon/7/"},
...
this.pokemonResourcesis still empty if I chain .subscribe -this.getListOfPokemonUrls().subscribe();, y is a type subscriber not observable but still no luck in storing the data in my array