Home > Software design >  How to fix rxjs catchError return type for http call in angular?
How to fix rxjs catchError return type for http call in angular?

Time:12-04

Inside my service I have a post method in which return type is IInfluencerRewardSetup

influencerRewardSetup(payload: IInfluencerRewardSetup): Observable<IInfluencerRewardSetup> {
    return this.httpClient.post<IInfluencerRewardSetup>(this.baseUrl, payload)
      .pipe(retry(1),
      this.errorHandler());
  }

and

private errorHandler() {
    return catchError(err => {
      this.notificationService.error(err.message, '');
      throw new Error(err.message || 'Server error');
    });
  }

But the problem is I am having this type of error:

Type 'Observable<unknown>' is not assignable to type 'Observable<IInfluencerRewardSetup>'

Please note that, errorHandler will handle other HTTP calls as well. Why am I having this error and how can I fix that type of issue here? can someone please help?

CodePudding user response:

Your catchError returns an Observable of type unknown, not IInfluencerRewardSetup. You could fix this with a cast:

return this.httpClient.post&lt;IInfluencerRewardSetup&gt;(this.baseUrl, payload)
      .pipe(retry(1),
      this.errorHandler() as Observable&lt;IInfluencerRewardSetup&gt;);

or by changing the catchError to return an Observable of the right type:

private errorHandler() {
    return catchError&lt;IInfluencerRewardSetup&gt;(err =&gt; {
      this.notificationService.error(err.message, '');
      throw new Error(err.message || 'Server error');
    });
  }

CodePudding user response:

The error comes from you have made the function with no parameters. And the operation in a pipe need an needs inputs and i believe outputs are optional. but in general have outputs too.

this answer is good to show how you should structure it https://stackoverflow.com/a/50908353/1805974 so for you it would probably look a bit like this:

handleError = () => pipe(
    catchError(err => {
      this.notificationService.error(err.message, '');
      throw new Error(err.message || 'Server error');
    });
  ); 

you need to import { pipe } from "rxjs"; as suggested in the answer

  • Related