flyingpluto7
flyingpluto7

Reputation: 1099

How to control or filter the number of objects being returned from emitted collection in rxjs observables?

service.$post() my observable from a service of return type <Observable<any[]>>, emits this collection

[{ name: 'nike' }, { name: 'nika' }, { name: 'niko' }, { name: 'niky' }]

this.posts = <Observable<any[]>>this.service.$post();

// result
// [{  name: 'nike' }, {  name: 'nika' }, {  name: 'niko' }, {  name: 'niky' }]

My question is how can I control or filter the number of objects being returned from emitted collection, in the example below I want to take 2 objects from <Observable<any[]>>this.service.$post(). Please help

this.posts = this.service.$post()
  .pipe(
    take(2)
  );

// should be
// [{  name: 'nike' }, {  name: 'nika' }]

Upvotes: 1

Views: 47

Answers (2)

jithin john
jithin john

Reputation: 572

const x = 2;

return this.service.$post()
       .map(arr => arr.slice(0, x));

I think this will do

Upvotes: 0

Tomasz Kula
Tomasz Kula

Reputation: 16837

You can get the first element like this:

this.posts = this.service.$post()
  .pipe(
    map(arr => arr[0])
  );

take(1) operator would return only the first value emitted by your observable. In this case it would be the entire array. And since the post request only emits once, it wouldn't really be useful.

If you want to keep x number of items, you can do it like this:

const x = 2;

this.posts = this.service.$post()
  .pipe(
    map(arr => arr.slice(0, x))
  );

Upvotes: 2

Related Questions