Why HttpParams doesn't work in multiple line in angular 4.3

后端 未结 5 1492
Happy的楠姐
Happy的楠姐 2020-12-05 02:51

From Angular 4.3 they introduced HttpClient instead of Http. in HttpClient I can\'t use URLSearchParams for url query parameter . instead of

5条回答
  •  有刺的猬
    2020-12-05 02:59

    Actually @Maximus made a pretty good explanation about the immutability of the HttpParams object, and all you need is to simply replace the params with its clone inside the loop.

    Assuming that you have zero-to-many params available, stored in an array similar to the structure below:

    "params": [
      {
        "key": "p1",
        "value": "v1"
      },
      {
        "key": "p2",
        "value": "v2"
      }
    ]
    

    And according to the information above, the following helper function should help:

    export const getHttpParams = (params: Array): HttpParams => {
      let res = new HttpParams();
    
      for (const item of params)
        res = res.append(item.key, item.value);
    
      return res;
    };
    

    Usage

    const backend = 'http://httpstat.us/200';
    const params = getHttpParams(backend.params);
    
    return this.http.get(`${backend}`, { params });
    

    Hope it helps!

提交回复
热议问题