Angular gives error when trying to handle errors that come from API calls

Viewed 44

I am writing angular service class to hit APIs. When some Internal server error comes in response, I want to send error message to user. The services written for get, but giving this error.

core.js:6014 ERROR TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable. at subscribeTo (subscribeTo.js:40:1)

sample.component.ts

this.maintenanceService.getCurrentStatus(this.Id, fromDateToRest, 
toDateToRest).subscribe(
  (CurrentStatus: any) => {

    if (CurrentStatus && CurrentStatus.length > 0) {
       //do something
    }

    if (CurrentStatus && CurrentStatus.length == 0) {
      this.errorMessage = "No data!"
    }

    if (CurrentStatus && CurrentStatus.status == 500) {
      this.errorMessage = "Internal Server Error!"
    }
    
    else {
      this.errorMessage = "Vehicle not found!"
    }
  }
);

sample.service.ts

getCurrentStatus(Id: String, fromDateToRest:String, toDateToRest:String): Observable<any> {

let params;
params = Object.assign( { fromDateToRest, toDateToRest } )

const httpOptions = {
  params
}

return this.restService.get<any>(URL,httpOptions);
}

restService

get<T>(url: string, httpOptions?: {}) {
  return this.httpClient.get<T>(url , httpOptions);
}

I read same questions and still didn't get a solution.

2 Answers

When serve returns error response, you need to handle it in error callback method.

this.maintenanceService.getCurrentStatus(this.Id, fromDateToRest, toDateToRest).subscribe(
        (CurrentStatus) => {
            if (CurrentStatus && CurrentStatus.length > 0) {
                //do something
            } else if (CurrentStatus && CurrentStatus.length === 0) {
                this.errorMessage = "No data!"
            }
        },
        (error) => {
            console.log(error);
            // check error status code, if it is 500, then do some actions like you needed below
            if (error.status === 500) {
                this.errorMessage = "Internal Server Error!"
            }
        }
    );

This is what You suppose to pay more attention to You provided 'undefined' where a stream was expected

Which means exactly what it states. You did not provide any data to the service and than to the endpoint.

You have to check if in every step the data is passed correctly to another step, i.e. from component to service, from service to endpoint.

Related