0

I'm learning JavaScript and Angular and I'm trying to get 3 objects randomly from my API response. How Can I do it?

I already print the the results but I only want to print 3 names randomly.

HTML

<div *ngFor='let heroi of randomHeros'>
  {{heroi.name}}
  {{heroi.description}}
</div>

Component

randomHeros;

  ngOnInit() {
    this.getHeroiAleatoriamente();
  }

  getHeroiAleatoriamente() {
    this.heroiService.getTodosHerois()
    .subscribe(
      response => {
        response = response.data.results;
      }
    );
  }

Service

getTodosHerois(): Observable<any> {
    return this.httpClient.get(`${API}/characters${KEYS}`)
    .pipe(
      map(
        response => response
      ),
      (error) => error
    );   }
paulotarcio
  • 461
  • 1
  • 5
  • 20
  • Possible duplicate of [Getting a random value from a JavaScript array](https://stackoverflow.com/questions/4550505/getting-a-random-value-from-a-javascript-array) – Heretic Monkey Jul 10 '19 at 19:10
  • See also [How to randomize (shuffle) a JavaScript array?](https://stackoverflow.com/q/2450954/215552) – Heretic Monkey Jul 10 '19 at 19:11

1 Answers1

0

There are many ways to do this. I would probably do it inside a filter wherever you assign the value to randomHeros. Lodash has some nice utility functions that can help you filter and manage data from an observable. Check out sampleSize

.map(todosHerois => _.sampleSize(todosHerois, 3))

In your Service, you probably want to be more specific about the return value of getTodosHerois:

getTodosHerois(): Observable<Heroi[]> {

Ben Hulan
  • 537
  • 2
  • 7