【问题标题】:rxjs take operator - to limit results with async piperxjs 带运算符 - 使用异步管道限制结果
【发布时间】:2018-12-28 15:55:49
【问题描述】:

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

apihttp://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>

【问题讨论】:

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


    【解决方案1】:

        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 计算从流中发出的响应,并且不修改流数据本身。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      • 2020-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多