deathandtaxes deathandtaxes - 7 days ago 5
HTTP Question

RxJS best way to limit and return response results array

I'm using Angular 2's http service to get some data, the API returns 'n' number of results, but I only want to handle 'x' amount.

Considering that I don't have access to the API's endpoints (in order to create limit or findOne kind of methods) I'm trying the figure out the best way to handle the number of results that will be returned to the component that calls my HomeService's "loadLatest" method.

With this particular example, the response is an object that looks something like this:

{
success: true,
data: [Object, Object, Object],
user: 'testUser'
}


I'm only interested in the data array (say, get only the first two objects it contains).

If I wanted to get a single result I could do something like this:

import { Http, Headers } from '@angular/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

const URL = 'http://exampleapi.com/example';

@Injectable()
export class HomeService {
constructor(private _http: Http){}

loadLatest() {
return this._http.get(URL)
.map(res => res.json())
.map(({data}) => data[0]);
}
}


And it works (which doesn't necessarily mean it's actually ok)... However, I know there's got to be a better way to return, for instance, the first two objects within the data array in the response's object. Or the first three, or four... Or however many I want.

I read about the "take" method, however I do not believe it would actually work in this case...

This is where I'm subscribing to it and using the service within my component:

import { Component, OnInit } from '@angular/core';
import { HomeService } from './home.service';
import { Observable } from 'rxjs/Observable';

@Component({
selector: 'home',
templateUrl: './home.html'
})
export class HomeComponent implements OnInit {
// I used this typing because I originally only wanted a single item
// This might have to change
items: Observable<Object>

constructor(private homeService: HomeService){}

ngOnInit() {
this.homeService.loadLatest()
.subscribe(result => this.items = result);
}
}


As you can see, I want for the result to be an array with two objects, which I assign to this.items, so that I can iterate over these two objects using angular's *ngFor.

Any help would be greatly appreciated!
Thanks in advance!

Answer

You could use the slice method in the data array.

loadLatest() {
  return this._http.get(URL)
  .map(res => res.json())
  .map(({data}) => data.slice(0,2));
}
Comments