I had an error
So I am learning how to catch errors with the catchError function in angular htttp services I have a ts file that executes function handler errors
import { Injectable } from '@angular/core';
import { HttpErrorResponse } from "@angular/common/http";
@Injectable({providedIn: 'root'})export class ProcessHttpMsgService {
constructor() { }
public handelError(error: HttpErrorResponse| any){let errMsg: string;
if (error.error instanceof ErrorEvent) {
errMsg = error.error.message;
} else {
errMsg =`${error.status}- ${error.statusText || ''} ${error.error}`
}
return new Error(errMsg)
}}
And I have a service that uses this function:
import { Injectable } from '@angular/core';
import { Dish } from "../shared/dish";
import {catchError, Observable, scheduled} from 'rxjs'import { map } from "rxjs";import { HttpClient } from "@angular/common/http";
import { baseURL } from "../shared/baseurl";
import {ProcessHttpMsgService} from "./process-http-msg.service";
@Injectable({providedIn: 'root'})
export class DishService {
constructor(private http: HttpClient,
private processHttpMsgService:ProcessHttpMsgService){
}
getDishes(): Observable<Dish[]>{return this.http.get<Dish[]>(baseURL + 'dishes').pipe(catchError(this.processHttpMsgService))}
getDish(id: string): Observable<Dish>{return this.http.get<Dish>(baseURL + 'dishes/' + id)}
getFeaturedDish():Observable<Dish>{return this.http.get<Dish[]>(baseURL + 'dishes?featured=true').pipe(map(dishes => dishes[0]))}
getDishIds(): Observable<number[] | any>{return this.getDishes().pipe(map(dishes => dishes.map(dish => dish.id)))}
}
This is because you are trying to pass an service class to
catchError
.catchError
expects you to pass it a function. That function is then supposed to either throw a newError
, or return anObservable
.Something like: