Search code examples
angularrxjsangular-httpclientrxjs6angular-observable

rxjs take operator - to limit results with async pipe


i can't limit the showed result in the template using the rxjs take() operator, the template shows me always all records.

The api http://jsonplaceholder.typicode.com/users returns 10 elements, i'd like to take only four of them.

[service]
public getData(): Observable<User[]> {
    return this.http.get<User[]>(`http://jsonplaceholder.typicode.com/users`).pipe(
       take(4)
      );
  }

[component]
export class GridComponent implements OnInit {

  _data : Observable<User[]>;

  constructor(public _ds : DataService) {  
  }

  ngOnInit() {
    this._data = this._ds.getData();
  }
}

[template]
<tr *ngFor="let d of _data | async">
        <td>{{d.id}}</td>
        <td>{{d.name}}</td>
        <td>{{d.email}}</td>
        <td>{{d.phone}}</td>
</tr>

Solution

  •     return this.http.get<[any]>(`https://jsonplaceholder.typicode.com/users`).pipe(
          map(x => x.slice(0, 4)))

    This is the way that your service should look like.

    You are using the rxjs take operator, that will take the first 4 responses of a stream. So in your case it will return the first four responses from the server (that includes the first response of the server, that contains an array of 10 elements).

    To achieve the desired result (take the first four elements of the incoming array) you must use rxjs map operator in order to modify the incoming http result, like shown.

    In other words take counts the emitted responses from a stream and dosen't modify the stream data itself.