【问题标题】:Angular 5: Is there anything like $httpParamSerailizer that was available in AngularJS?Angular 5:AngularJS 中是否有类似 $httpParamSerailizer 的东西?
【发布时间】:2018-02-11 02:12:14
【问题描述】:

我正在尝试将对象序列化为查询参数。在AngularJS 中,我使用$httpParamSerializer

Angular 5 中有哪些内容?

【问题讨论】:

    标签: angularjs angular


    【解决方案1】:

    这是我对您的问题的看法。这使用HttpParamsOptionsHttpParamsHttpParamsOptions 将通过在 fromObject 属性中传递一个对象来构建参数。您可以在评论中看到进行 API 调用时的样子。

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpParams } from '@angular/common/http';
    import { HttpParamsOptions } from '@angular/common/http/src/params';
    
    @Injectable()
    export class ApiService {
      constructor(private httpClient: HttpClient) { }
    
      getThingsWithParams(): any { // you could pass your object in as a function parameter
          const myObject: any = { this: 'thisThing', that: 'thatThing', other: 'otherThing'};
          const httpParams: HttpParamsOptions = { fromObject: myObject } as HttpParamsOptions;
          const options = { params: new HttpParams(httpParams) };
          return this.httpClient.get<any>('http://localhost:34479/api/products/168', options);
          // This is what is sent to the API:
          // http://localhost:34479/api/products/168?this=thisThing&that=thatThing&other=otherThing
      }
    }
    

    我想这就是你所追求的。一种基于对象属性构建参数的方法。

    https://github.com/angular/angular/blob/530b824faa29460a87c2401bc61d22a7fb56f939/packages/common/http/src/params.ts#L76

    【讨论】:

    • 是的,通过查看 HttParams 的源代码使其工作,它需要'fromObject'。不过感谢您的努力。已接受答案。
    猜你喜欢
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多