[英]Is it possible to use rxjs take operator to limit observables returned from a service?
我对angular非常陌生,我正在网站上学习,该网站要求我在首页上列出4辆车的有限列表,因此我创建了一项提取所有车的服务,如下所示。
import { Response } from '@angular/http';
import { Car } from '../classes/car';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
@Injectable()
export class CarService {
rootURL = 'http://localhost:3000/cars';
constructor(private _http: HttpClient) {}
getCars(): Observable<Car[]> {
return this._http.get<Car[]>(this.rootURL);
}
}
然后在我的特色汽车组件上,我在组件初始化时访问该服务,如下所示
constructor(private _carService: CarService ) { }
ngOnInit() {
this._carService.getCars()
.take(4)
.subscribe(data => this.cars = data,
error => this.errorMessage = <any>error);
}
因此,精选的汽车组件可以工作,但是它为我提供了API中所有汽车的列表,而我只需要显示4辆汽车,我尝试使用Rxjs'take`运算符,但似乎不起作用吗? 哪里可能出问题了?
您可以使用JavaScript的slice
运算符。
ngOnInit() {
this._carService.getCars()
.take(4)
.subscribe(
data => this.cars = data.slice(0, 4),
error => this.errorMessage = <any>error);
}
完成之前,请发出提供的值数。
为什么要用
当您仅对第一个设置的发射数量感兴趣时,您想使用take。 也许您想查看用户首次进入页面时第一次点击的内容,您可能希望订阅click事件并只进行第一次发射。 有一场比赛,您想观看比赛,但是您只对第一个越过终点线感兴趣。 该运算符明确而直接,您只想查看前n个发射数即可完成所需的任何操作。
'take'运算符不用于限制返回数组中的数据数量。 您可以使用普通的JavaScript函数Array.slice来操纵数组。
ngOnInit() {
this._carService.getCars()
.subscribe(data => this.cars = data.slice(0, 4),
error => this.errorMessage = <any>error);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.