简体   繁体   中英

Is it possible to use rxjs take operator to limit observables returned from a service?

I am very new to angular and i'm learning by working on website that requires me to list a limited list of 4 cars on the home page, so i created a service that fetches all the cars as shown below.

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);
}
}

and then on my featured cars component, i access the service on component initialization,like shown below

constructor(private _carService: CarService ) { }

ngOnInit() {
  this._carService.getCars()
  .take(4)
  .subscribe(data => this.cars = data,
  error => this.errorMessage = <any>error);
}

So the featured cars components works but it gives me a list of all the cars from the API while i only need to show 4 cars, i have tried using Rxjs 'take` operator and doesn't seem to work? where might be going wrong?

You can use JavaScript's slice operator.

ngOnInit() {
  this._carService.getCars()
  .take(4)
  .subscribe(
     data => this.cars = data.slice(0, 4),
     error => this.errorMessage = <any>error);
}

Emit provided number of values before completing.

Why use take

When you are interested in only the first set number of emission, you want to use take. Maybe you want to see what the user first clicked on when he/she first entered the page, you would want to subscribe to the click event and just take the first emission. There is a race and you want to observe the race, but you're only interested in the first who crosses the finish line. This operator is clear and straight forward, you just want to see the first n numbers of emission to do whatever it is you need.

taken from learn-rxjs

the 'take' operator isn't used to limit the number of data from the returned array. You could use a normal JavaScript function Array.slice to manipulate the array.

ngOnInit() {
    this._carService.getCars()
    .subscribe(data => this.cars = data.slice(0, 4),
    error => this.errorMessage = <any>error);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM