How to use Skip and Take with RxJs Observable

I am learning Angular 2, TypeScript, RxJs, etc., and I am having trouble returning a subset of the data inside the service using RxJs and Observable.

I expect the getCars function below to read the json file, parse it and return a piece of data (offset and count). However, I always get all the data back (I have 200 objects / machines in the file I'm testing).

What am I doing wrong?

EntityService

@Injectable() export class EntityService { constructor(private http: Http) { } getCars(offset: number, count: number): Observable<Car[]> { return this.http .get('resources/data/cars.json') .map(this.extractData) .skip(offset) .take(count) .catch(this.handleError); } private extractData(res: Response) { let body = res.json(); return body.data || {}; } private handleError(error: any) { // ... } } 

cars.json

  { "data":[ { "vin":"ee8a89d8", "brand":"Fiat", "year":1987, "color":"Maroon" }, { "vin":"642b3edc", "brand":"Renault", "year":1968, "color":"White" } ] } 
+7
javascript angular typescript rxjs
source share
1 answer

In fact, you will always download all the data using this. The skip and take statements only apply if several events are received in the data stream:

  • skip : skip multiple events
  • accept : consider only a certain number of events

In your case (HTTP request) you have only one: when you receive the data. Therefore, if you want to filter data, you need to use another map operator. Something like that:

 getCars(offset: number, count: number): Observable<Car[]> { return this.http .get('resources/data/cars.json') .map(this.extractData) .map(data => { return data.slice(offset, offset + count); // <---- }) .catch(this.handleError); } 
+7
source share

All Articles