如何设置返回类型 Observable?

How to set returning type Observable?

我有以下代码:

  public check(data: ProjectSettings): Observable<boolean> {
    return this.http.post(this.checkProjectUrl, data);
  }

我收到这样的错误:

Type 'Observable' is not assignable to type 'Observable'. Type 'Object' is not assignable to type 'boolean'.

如何解决这个问题?

   public check(data: ProjectSettings): Observable<T> {
        return this.http.post<T>(this.checkProjectUrl, data);
      }

您可以通过post<T>投射价值。在 Angular 文档中,您可以找到 "Overload #8".

https://angular.io/api/common/http/HttpClient#post

public check(data: ProjectSettings): Observable<boolean> {
   return this.http.post<boolean>(this.checkProjectUrl, data);
}

默认情况下 HttpClient return 中的 HTTP 方法 object 作为 Observable。您需要将类型更改为 boolean 到 return a boolean 作为 Observable.

  public check(data: ProjectSettings): Observable<boolean> {
    return this.http.post<boolean>(this.checkProjectUrl, data);
  }