Jestem nowy w Angular, próbuję obsłużyć błąd ale funkcja Observable zachowuje się tak jak by za każdym razem było powodzenie.
W przypadku błędu po prostu result jest pusty;
(To jest przykład z Tutoriala)
// (method) Observable<Hero[]>.subscribe(
// next?: (value: Hero[]) => void,
// error?: (error: any) => void,
// complete?: () => void): Subscription (+1 overload)
getHeroes(): void {
this.heroService.getHeroesFromServer()
.subscribe(
result => { //next
console.log('next is WORKING');
this.heroes = result;
},
error => { // error TA FUNKCJA SIĘ NIE WYKONUJE w przypadku błędu
alert('ERROR');
},
() => { //complete
console.log('complete is WORKING');
},
);
}
/** GET heroes from the server */
getHeroesFromServer(): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
tap(_ => this.log('fetched heroes')),
catchError(this.handleError('getHeroes', []))
);
}
/**
* Handle Http operation that failed.
* Let the app continue.
* @param operation - name of the operation that failed
* @param result - optional value to return as the observable result
*/
private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// TODO: better job of transforming error for user consumption
this.log(`${operation} failed: ${error.message}`);
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
Pryzychodzi mi do głowy jedynie takie rozwiązanie:
getHeroes(): void {
this.heroService.getHeroes()
.subscribe(result => {
if (result) {
this.heroes = result;
} else {
alert('ERROR');
}
});
}
Jak zrobić, żeby handleError zwracał błąd?
Jak poprawnie się to robi?
Proszę naprowadzić mnie na właściwe rozwiązanie.