Error in catchError tutorial Tour of Heroes of Angular 6

Asked

Viewed 114 times

0

I’m new to the angle, and I’m following the tutorial Tour of Heroes of Angular 6 and having trouble with the catchError of an Observable. 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 this moment, 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 ta OK, so much so that this error happened after I inserted the catchError, but I’m not getting the list of heroes.

  • On the line catchError(this.handleError<Hero>(\getHero id=${id}`))não seriacatchError(this.handleError(`getHero id=${id}`))ou ``catchError(this.handleError.bind(this,getHero id=${id}`))`` ?

  • Worse than not, the error continues.

  • where is the code of the handleError method?

1 answer

0

Try using the 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([]))
      );
  }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.