Http options in Angular 4.3

I am trying to use the new http client that came out with Angular 4.3. I checked the docs and used the HttpParams class, but it doesn't seem to work, or am I doing something wrong. Here is what I have:

 delete(personId: string) { const params = new HttpParams(); params.set('personId', personId); return this.http.delete(`${this.baseUrl}`, { params }); } 

But when executing the request in my url there are no request parameters Any help would be appreciated

+5
source share
2 answers

Parameters are now immutable , so you must set them when starting new HttpParams so that each set () returns a new instance and applies the changes. Try

 const params = new HttpParams() .set('personId', personId); 

Here are the docs that cover the headers and URL parameters for 4.3 - https://angular.io/guide/http#headers


Edit: I wanted to update my answer and indicate that you do not have to set parameters when starting the HttpParams class. For example, if you need to set parameters in a for loop or outside of HttpParams initialization, you can do this with

 const params = new HttpParams() .set('personId', personId); params = params.set('personName', personName); 

As stated in the docs:

The HttpHeaders class is immutable, so each set () returns a new instance and applies the changes.

+9
source

HttpParams is immutable.

set() creates and returns a new instance of HttpParams without changing the instance on which set() called.

So the code should be

 const params = new HttpParams().set('personId', personId); 

Here is another thing that I came across when using these new HttpParams, sometimes we have n number of parameters to pass, then it is useful to have some function that converts the parameter object (which we used before Angular 4.3) to HttpParams.

I suggest making the toHttpParams function in your frequently used service. So you can call a function to convert the object to HttpParams .

 /** * Convert Object to HttpParams * @param {Object} obj * @returns {HttpParams} */ toHttpParams(obj: Object): HttpParams { return Object.getOwnPropertyNames(obj) .reduce((p, key) => p.set(key, obj[key]), new HttpParams()); } 

Update:

Starting with 5.0.0-beta.6 (2017-09-03), they added a new function ( accept the object map for the headers and parameters of HttpClient )

Upon transition, the object can be passed directly instead of HttpParams.

This is another reason, if you used one common function like toHttpParams mentioned above, you can easily remove it or make changes if necessary.

+1
source

Source: https://habr.com/ru/post/1270326/


All Articles