in the Angular tutorial, how do you modify the log line to specify the number of heroes fetched?

46 Views Asked by At

The code example is this:

/** GET heroes from the server */
getHeroes(): Observable<Hero[]> {
  return this.http.get<Hero[]>(this.heroesUrl)
    .pipe(
      tap(_ => this.log('fetched heroes')),
      catchError(this.handleError<Hero[]>('getHeroes', []))
    );
}

The tutorial notes "The RxJS tap() operator enables this ability by looking at the observable values, doing something with those values, and passing them along. The tap() call back doesn't access the values themselves."

Anyway, I want something like this:

this.log('fetched {{heroes.size}} heroes')

but I can't get my hands on heroes. How do I do this?

1

There are 1 best solutions below

0
Andrew Allen On BEST ANSWER

Note in javascript, 'fetched {{heroes.size}} heroes' will just be a literal string .

I've shown a console.log below as @enno.void mentions

/** GET heroes from the server */
getHeroes(): Observable<Hero[]> {
  return this.http.get<Hero[]>(this.heroesUrl)
    .pipe(
      tap((heroes) => console.log(`fetched ${heroes.length} heroes`)),
      catchError(this.handleError<Hero[]>('getHeroes', []))
    );
}

Tap does not affect the subsequent stream and can (avoid as much as possible) be used for side effects.