'Angular TypeError: You provided 'undefined' where a stream was expected

I am trying to fetch a log by it's id but I am getting a TypeError. This is my code:

export class LogComponent implements OnInit {

  id!: number;

  logs!: Log[];
  log!: string

  constructor(private logService: LogService) {
  }

  public show: boolean = false;
  public buttonName: any = 'Load message';

  ngOnInit() {
    this.logService.getLogs().subscribe((data: Log[]) => {
      console.log(data)
      this.logs = data

    })

  }

  showLog() {
    this.show = !this.show;
    this.logService.getLogById(this.id).subscribe((data: Log) => {
      console.log(data)
      // @ts-ignore
      this.log = data;
      if (this.show)
        this.buttonName = "Hide";
      else
        this.buttonName = "Load message";
    })
  }

  
}

And this is my service component :

getLogById(id:number): Observable<Log> {
    // @ts-ignore
    return this.http.get<Log>(`${this.API}/${id}`).pipe(catchError(this.handleError
    ));
  }

  private handleError(httpErrorResponse:HttpErrorResponse){
    if(httpErrorResponse.error instanceof ErrorEvent){
      console.error(httpErrorResponse.error.message)
    }

The error that I am getting is :

TypeError: You provided 'undefined' where a stream was expected.
GET http://localhost:8081/logs/undefined

The error is showing the Id an an undefined. any solutions ?



Solution 1:[1]

My take on this is that the problem happens because you don't return anything from catchError.

The log ID that you are providing to your service method, is likely undefined as seen in your console log GET http://localhost:8081/logs/undefined and your backend returns an error because it cannot find the log with id undefined and the catchError triggers in this case.

You can return null or an empty object when your backend throws an error:

private handleError(httpErrorResponse:HttpErrorResponse){
  if(httpErrorResponse.error instanceof ErrorEvent){
    console.error(httpErrorResponse.error.message)
  }
  return of(null); // or return of({} as Log);
}

If you start to get type errors because your service method is only supposed to return an instance of Log (strict null checks) then you can change the type of the return value:

getLogById(id:number): Observable<Log | null>

And make sure to adjust the code that calls this method too, to account for the fact that now the returned log can be null.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Octavian Mărculescu