Is it possible to take only a certain number of elements of an http call after I modify the original response with a ‘map’ operator?
For example, let’s say I have this very simple http call for the Rick And Morty API:
Simple two interfaces:
export interface Character {
id: number;
name: string;
status: string;
species: string;
type: string;
gender: string;
origin: Origin;
location: Location;
image: string;
episode: string[];
url: string;
created: string;
}
export interface RickAndMortyResponse {
info: Info;
results: Character[];
}
Now if I do the call, it’s mandatory to do it with the ‘RickAndMortyResponse’, but in my final response I just care about the first two elements of the ‘results’ response, so the logic thing to do would be this:
export class RickAndMortyService {
private http = inject(HttpClient);
characters$ = this.http
.get<RickAndMortyResponse>('https://rickandmortyapi.com/api/character')
.pipe(
map((response) => response.results),
take(2)
);
}
However, this stills retrieving all the data of ‘results’, I presumed It’s because the ‘take’ operator affects the ‘RickAndMortyResponse’ and not the ‘results’ array.
So to solve this, the only way I see is to do a slice on the map operator:
characters$ = this.http
.get<RickAndMortyResponse>('https://rickandmortyapi.com/api/character')
.pipe(map((response) => response.results.slice(0, 2)));
So, is there any way to actually use operators like ‘take’ after I modified the original stream of data using ‘map’?