【问题标题】:Observable of HttpClient can not map correctly from HttpResponseHttpClient 的 Observable 无法从 HttpResponse 正确映射
【发布时间】:2019-04-25 12:35:52
【问题描述】:

我在 angular7 中获得了一项服务,它给了我一些密钥:

  getList(
    pageSize: number = 30,
    pageNumber: number = 0,
    filters: CKeyListFilters = <CKeyListFilters>{},
    sortByKey: string = 'activeTo',
    sortOrder: SortOrder = SortOrder.DESC
  ): Observable<ListPaginated<CKey[]>> {
    // ....

    return this.http
      .get<ListPaginated<CKey[]>>(`${environment.CApiUrl}/Get`, {
        params: params,
        observe: 'response',
      })
      .pipe(
        map((resp: HttpResponse<CKey[]>) => {
          return {
            content: resp.body,
            pagination: this.utilities.getPaginationMetaData(resp),
          } as ListPaginated<CKey[]>;
        }),
        catchError((error) => {
          throw error;
        })
      );
  }

但是在pipe 方法中我得到了这个错误:

error TS2345: Argument of type 'OperatorFunction<HttpResponse<CKey[]>, ListPaginated<CKey[]>>' is not assignable to parameter of type 'OperatorFunction<HttpResponse<ListPaginated<CKey[]>>, ListPaginated<CKey[]>>'.

所以我想将HttpResponse&lt;CKey[]&gt; 映射到ListPaginated&lt;CKey[]&gt; 但我不知道如何转换它。

我继承了这段代码,我是typescript 的新手,所以任何建议对我都有用!

【问题讨论】:

  • 能否提供导入map的行?
  • @mbojko 当然!来自import { catchError, map } from 'rxjs/operators';
  • 哦。我的假设是错误的map 是从 rxjs 导入的。但它似乎是正确的。

标签: angular typescript httpclient angular7


【解决方案1】:

好的。这里是:

      .get<ListPaginated<CKey[]>>(`${environment.CApiUrl}/Get`, {
        params: params,
        observe: 'response',
      })
      .pipe(
        map((resp: HttpResponse<CKey[]>) => {

在第 1 行,请求的资源是 ListPaginated&lt;CKey[]&gt; 类型。在第 6 行,map 的参数是 HttpResponse&lt;CKey[]&gt; 类型。这些类型必须匹配(或者您可以完全从map 中删除resp 的输入)。

【讨论】:

  • 你是对的! :) 谢谢。我不得不写.get&lt;CKey[]&gt;(...)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-12
  • 2023-04-01
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 2018-04-01
  • 1970-01-01
相关资源
最近更新 更多