3

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;
}

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that makes sense. Could you expand how to limit the response in the .map with equivalent of .take what I'm trying to achieve?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.