ale*_*lex 0 rxjs angular angular-observable angular-httpclient rxjs6
我无法使用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>
Run Code Online (Sandbox Code Playgroud)
return this.http.get<[any]>(`https://jsonplaceholder.typicode.com/users`).pipe(
map(x => x.slice(0, 4)))Run Code Online (Sandbox Code Playgroud)
这是您的服务应该是这样的方式.
您正在使用rxjs take运算符,它将获取流的前4个响应.因此,在您的情况下,它将返回来自服务器的前四个响应(包括服务器的第一个响应,其中包含10个元素的数组).
要获得所需的结果(获取传入数组的前四个元素),必须使用rxjs map运算符来修改传入的 http结果,如图所示.
换句话说,take 计算来自流的响应并且不会修改流数据本身.