代码之家  ›  专栏  ›  技术社区  ›  Brian

使用类在angular.io中将查询参数传递给httpclient

  •  0
  • Brian  · 技术社区  · 6 年前

    我读过 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}开头,并分解为:

    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';
    }
    

    以下是供参考的httpparams选项:

    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;
    }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   user4676340user4676340    6 年前

    既然你有弦乐,为了让它简单,我建议你改为这样做:

    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';