简体   繁体   中英

Angular2 RxJs: simple take() from http returned observable

I simply try to .take(5) from an http returned observable:

this.dataObservable = this._service.getData()
                                   .take(5);

and use it in HTML like so:

<tr *ngFor="let record of dataObservable | async">

This works. But I get all the records, I just want 5. What am I doing wrong? Thanks.

In the _service I return the http observable:

getData(): Observable<any> {
  url = '/getData';
  this._data = this._http.get(url)
    .map(response => this.extractData(response));
  return this._data;
}

This .take(5) will take 5 emits of your Observable, not 5 elements of that containing data.

You should limit it to 5 in your .map function.

Or .subscribe to that observable and in that function you will limit incoming data in store it in a local variable which will be bound to your template.

getData(): Observable<any[]> { // returns an array, right??
  url = '/getData';
  this._data = this._http.get(url)
    .map(response => this.extractData(response));
  return this._data;
}

// in your component

this.yourService.getData().subscribe(
   dataArray => this.data = dataArray.slice(0, 5),
   err => console.log(err)
);

this.data will be bound to your template.

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