【问题标题】:Using a class to pass query parameters to HttpClient in Angular.io在 Angular.io 中使用类将查询参数传递给 HttpClient
【发布时间】:2018-12-15 02:31:34
【问题描述】:

我读过 in this post 我可以在 HttpParamsOptions 中使用 fromObject 将对象用作查询中的查询参数。不幸的是,我在让对象处于正确形状时遇到了一些问题。我认为它能够使用一个具有所有类型字符串的对象,并且不确定如何将其转换为正确的形状。我宁愿不必遍历对象键来让东西适合这个盒子——如果我必须这样做,它就会失去所有的价值。

谁能向我解释这里发生了什么?我已经阅读了有关可索引类型的信息,但这并没有帮助我弄清楚如何将其应用于这种情况。

报告类型错误:

TS2322: Type '{ fromObject: Query; }' is not assignable to type 'HttpParamsOptions'. 
  Types of property 'fromObject' are incompatible.
    Type 'Query' is not assignable to type '{ [param: string]: string | string[]; }'.
      Index signature is missing in type 'Query'.

调用站点(get 中以 {params: query} 开头并分解为 this):

public retrieve(query: Query): Observable<PolicyRetrieveResult> {
  const q: HttpParamsOptions = {fromObject: query};
  const params = new HttpParams(q);
  return this.http.get<Result>(url, {params: params});
}

我的查询类:

export class Query {
  id: string;
  source: string = 'constant';
  type: string = 'otherConstant';
}

这里是 HttpParamsOptions 供参考:

export interface HttpParamsOptions {
    /**
     * String representation of the HTTP params in URL-query-string format. Mutually exclusive with
     * `fromObject`.
     */
    fromString?: string;
    /** Object map of the HTTP params. Mutally exclusive with `fromString`. */
    fromObject?: {
        [param: string]: string | string[];
    };
    /** Encoding codec used to parse and serialize the params. */
    encoder?: HttpParameterCodec;
}

【问题讨论】:

  • HttpParamsOptions 不是公共角度类型。你不应该使用它。你想达到什么目的?
  • 我正在努力实现这一目标:this.http.get(url, {params: query});其中 query 是我定义的一个类

标签: angular


【解决方案1】:

既然你有字符串,为了简单起见,我建议你做这样的事情:

public retrieve(query: Query): Observable<PolicyRetrieveResult> {
  return this.http.get<Result>(url, {params: {...query}});
}

以后,如果你有非字符串对象,正确的语法是

params: HttpParams = new HttpParams({ fromObject: query })

不要使用HttpParamsOptions,当你看到它来自哪里你就会明白为什么:

import { HttpParamsOptions } from '@angular/common/http/src/params';

【讨论】:

  • 新的HttpParams异常同上TS2345: Argument of type '{ fromObject: Query; }' is not assignable to parameter of type 'HttpParamsOptions'. Types of property 'fromObject' are incompatible. Type 'Query' is not assignable to type '{ [param: string]: string | string[]; }'. Index signature is missing in type 'Query'.
  • 输入为any,您是否尝试过第一个解决方案?
  • 应该是{params: { ...query } }
  • 使用扩展运算符?是的,它不喜欢它。从我读过的内容来看,即使没有展开运算符,它也应该可以工作,但无论我把参数放在哪里,我都会得到括号中的类型错误:现在从扩展运算符中获取错误
  • 哦,我的错,我没看到我忘记了一组括号!它之所以有效,是因为它是正确的语法,扩展运算符解构一个对象。这相当于手动重新编写所有属性,因此您需要将其用括号括起来,就好像它是一个对象一样。我编辑了我的答案,谢谢你的修改!
猜你喜欢
  • 2021-11-27
  • 2018-02-16
  • 2017-09-27
  • 2014-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-26
相关资源
最近更新 更多