简体   繁体   中英

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' }]

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))
  );
const x = 2;

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

I think this will do

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM