rxjs接受运算符-使用异步管道限制结果

时间:2018-07-20 10:45:41

标签: angular rxjs angular-httpclient rxjs6 angular-observable

我无法使用rxjs take()运算符来限制模板中显示的结果,该模板始终向我显示所有记录。

api http://jsonplaceholder.typicode.com/users返回10个元素,我只希望其中四个。

[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>

1 个答案:

答案 0 :(得分:7)

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

这就是您的服务的外观。

您正在使用rxjs take运算符,该运算符将获取流的前 4个响应。因此,在您的情况下,它将返回服务器的前四个响应(包括服务器的第一个响应,其中包含10个元素的数组)。

要获得所需的结果(采用传入数组的前四个元素),必须使用rxjs map运算符,以便修改传入的 http结果,如图所示。

换句话说,take 计算流中发出的响应,并且不修改流数据本身。