Error in catchError of the tutorial Tour of Heroes of Angular 6

0

I'm a beginner in the angular, and I'm following the Tour of Heroes tutorial on Angular 6 and having problems with an Observable's catchError. This is the error that VSCODE sends me:

Type 'Observable<{} | Hero[]>' is not assignable to type 
'Observable<Hero[]>'.
  Type '{} | Hero[]' is not assignable to type 'Hero[]'.
    Type '{}' is not assignable to type 'Hero[]'.
      Property 'includes' is missing in type '{}'.

My code is not complete, but until then, according to the tutorial, things should work.

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';

import { Hero } from './hero';

import { MessageService } from './message.service';

@Injectable({
  providedIn: 'root'
})
export class HeroService {



  constructor(private messageService: MessageService,
              private http: HttpClient
  ) { }

  private heroesUrl = 'api/heroes';

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

    /** GET hero by id. Will 404 if id not found */
  getHero(id: number): Observable<Hero> {
    const url = '${this.heroesUrl}/${id}';
    return this.http.get<Hero>(url).pipe(
      tap(_ => this.log('fetched hero id=${id}')),
      catchError(this.handleError<Hero>('getHero id=${id}'))
    );
  }

  private log(message: string) {
    this.messageService.add('HeroService: ' + message);
  }


}

This is my Hero class:

export class Hero {
    id: number;
    name: string;    
}

In short, the rest of the code is OK, so much so that this error happened after I inserted catchError, but I'm not getting the list of heroes.

    
asked by anonymous 12.05.2018 / 23:50

1 answer

0

Try using of .

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