Angular catchError 和 return 可观察

Angular catchError and return observable

我有一个模型class代表我的服务器响应:

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

当我调用我的 api 时,我希望响应总是 Observable<ServerResponse>,发生错误时也是如此:

callApi() : Observable<ServerResponse> {

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

但是我遇到了这个打字稿错误:

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

为什么of方法returnsObservable<Object | ServerResponse>?

谢谢

post方法添加类型:

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

如果您不通知它,Typescript 无法推断从 post 返回的类型。来自 source code(以及您可以在那里查看的其他签名):

  /**
   * 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>>;