Home > Software engineering >  Angular catchError and return observable
Angular catchError and return observable

Time:04-20

I have a model class represents my server response:

class ServerResponse {
  code: number;
  response: string;
}

When I call my apis I would like the response to be always Observable<ServerResponse>, also when an error occur:

callApi() : Observable<ServerResponse> {

  return this.http.post(this.endpoint, '')
    .pipe(
      // ....
      catchError(err => {
        // ...
        return of(new ServerResponse());
      }
     )
}

But I got this typescript error:

Type 'Observable<Object | ServerResponse>' is not assignable to type Observable<ServerResponse>

Why do of method returns Observable<Object | ServerResponse>?

Thanks

CodePudding user response:

Add a type to the post method:

this.http.post<ServerResponse>(this.endpoint, '')

Typescript has no way of inferring the type returned from the post if you don't inform it. From the source code (among other signatures that you can check there):

  /**
   * Constructs a POST request that interprets the body as a JSON object and returns the full event
   * stream.
   *
   * @param url The endpoint URL.
   * @param body The content to replace with.
   * @param options HTTP options
   *
   * @return An `Observable` of all `HttpEvent`s for the request,
   * with a response body in the requested type.
   */
  post<T>(url: string, body: any|null, options: {
    headers?: HttpHeaders|{[header: string]: string | string[]}, observe: 'events',
    context?: HttpContext,
    params?: HttpParams|
          {[param: string]: string | number | boolean | ReadonlyArray<string|number|boolean>},
    reportProgress?: boolean,
    responseType?: 'json',
    withCredentials?: boolean,
  }): Observable<HttpEvent<T>>;
  • Related