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

Time:01-06

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?

CodePudding user response:

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.

  • Related