New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
common/http: HttpClient and params #18012
Comments
|
@jnizet Right, I updated the issue |
Why can't we just use an arbitrary object? It was so much easier |
I think it will be good if you add more info about immutable
=> Because working with HttpParams for me was confused. |
@DmitryKrekota if you need multiple params on object use .append('param', 'value'). |
@CDDelta how would you do this if you have an N number of parameters going into the get request ?before with the old http you could have just used a for in loop. I am assuming this is not the case anymore. |
@PodaruDragos HttpParams is immutable so in order to use it with a loop you will have to do something like this:
|
I'm having a similar problem: And the request I get is: Obviously not working |
Noticed this inconvenience too, here is the snippet to convert an function toHttpParams(params) {
return Object.getOwnPropertyNames(params)
.reduce((p, key) => p.set(key, params[key]), new HttpParams());
}
// Example:
toHttpParams({firstName: 'John', lastName: 'Doe'}); |
This should be soon fixed by #18490 |
I have a problem with not easy key value pair... what if I wanted to set for a value an object? I am having this problem:
when I get the headers thens et to but for some reason, the : doesn't get encoded and the string should've been any ideas how to solve this? |
This was fixed by #18490 and released in |
Can anyone enlighten me as to why one should parse parameters into this new HttpParams instance only to convert it back into a string in the POST body? It seems more logical to just convert my parameters into a single string initially, rather than creating some cumbersome immutable object multiple times. What value does the HttpParams add? It seems that in order to use it throughout an application, I would need to extend it. |
If i use loop for append parameters to HttpParams it copy a param many times! |
Can anyone tell me the basic difference of set() and append() method??? What one should prefer over other??? |
@Agrumas Thanks a lot ,This solve my question.To be honest,I still confuse about the work of httpParams . |
I have the same issue. I just switched to Angular 5 and adjusted my code accordingly:
But, result url doesn't contain parameters! Any idea how to fix that? |
@alekseytimonin HttpParams is immutable. Its set() method returns a new HttpParams, without mutating the original one. Your code should be
Or simply
Also note that you can simply pass a simple JavaScript object now. |
I am having the same issue with @fpl1976, simply put the the params but the generated request url looks so weird like "updates=%7B%22param%22:%22lang%22,%22value%22:%22en%22,%22op%22:%22s%22%7D&cloneFrom=%7B%22updates%22:null,%22cloneFrom%22:null,%22encoder%22:%7B%7D" currently I have to remove the usage of HttpParams and generate the request in string but it feels bad by doing that.. Best |
@kevinding0218 with angular version 5 or higher it is solved |
@fpl1976 , thank you! However, I am actually using Angular 5.0.0 and this is what happened to me, is there any part of the code that should be changed? |
@kevinding0218 I'm using 5.1.0, try to upgrade |
@cexbrayat const params = new HttpParams({
fromObject: {
pageNumber: 1,
dateFrom: new Date(),
onlyActive: true
}
}) it will show typescript error because fromObject is just Now developers will need to write utils to simply convert plain object to http params. import { HttpParams } from '@angular/common/http';
export function toHttpParams(obj: Object): HttpParams {
let params = new HttpParams();
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const val = obj[key];
if (val !== null && val !== undefined) {
params = params.append(key, val.toString());
}
}
}
return params;
} const myListFilter = {
pageNumber: 1,
contractId: '#aaab',
onlyActive: true
};
const params = toHttpParams(myListFilter); // oh finally Would it be possible to allowing to set number, boolean, datetime? |
Still not working on Doing the follow code, nothing happens, not even error
But just mounting the query, it works
So, it seems that the problem it's with In resume This is not woking (no request is fired)
This is working
|
@rochapablo , I figured out why it's not working, the HttpParams seems only work with HttpClient not Http, so in your service when inject the http you can try to refer HttpClient(import { HttpClient } from '@angular/common/http';) instead of Http |
But it's what I'm doing =/
|
@rochapablo , when you mean "no error", could you check if the request was successfully responded or some error code returned (e.g Chrome Network tab) if possible, or did it even hook up the api/service method if you could set a debug break point there? |
@CDDelta ... You are right.
|
@jwhijazi you can actually provide an object to the http client instead of a HttpParams now. You will need to update Angular though. |
@CDDelta |
@jwhijazi introduced in 5.0.0 |
how about a static factory method?
|
@MrAntix Why wrap an object to |
@trotyl I guess a use case would be where you have an object you want to start with, and then append
Fact is the API is pretty tough, everything has to be a string - which I know is the ultimate goal, but having something to handle serialisation generally would be helpful. If not, a global extension point which is easily implemented would be good. In the meantime we can inject our own service to map from our own objects to HttpParams. Fact is, I've become used to the framework handling this - guess I'm getting lazy in my old age :D Totally fine with the immutable ideal btw. |
@MrAntix Objects can also be changed quickly: var params = Object.assign({}, myObject, { index: '10', count, '100' }) Or just mutate it: Object.assign(myObject, { index: '10', count, '100' }) The immutability may be a good restriction for For supporting non-string types, there's some discussion in #20316 (and linked PRs). |
|
I also would like to see a So who want to help me to add this to the code archive? toObject() {
return this.keys().reduce((obj, key) => {
obj[key] = this.get(key);
return obj;
}, {});
} For an array use: toArray() {
return this.keys().map(x => ({ [x]: this.get(x) }));
} |
Can someone explain how this is still an issues? How can it be, this use-case doesn't work:
|
@lordgreg its not an issue. Also FYI you should be able to just pass an object to |
@CDDelta thank you for your response. However, if my
What would you expect to output? 3 previous params + 1 new in Does this make sense? Of course not. Is there a use-case where this would make sense? I cannot find a single. Does |
@lordgreg This is by design the case. Try it like this: const p = new HttpParams();
p = p.append('foo', 'bar');
p = p.append('abc', '123'); Or: const p = new HttpParams().set('foo', 'bar').set('abc', '123'); |
Any news regarding number and boolean support? Or we just end up using excessive convert utils? |
to add the params in this following lines |
Im using let httpParams = new HttpParams().set('name', term); Any help ? |
how to append custom headers and also params with get request of @angular/common/http ? |
@Injectable()
export class YourInterceptor implements HttpInterceptor {
constructor() {}
intercept( req: HttpRequest<any>, next: HttpHandler ):
Observable<HttpEvent<any>> {
req = req.clone( { withCredentials: true } ); // Add your Custom Headers
return next.handle( req )
.do( event => {
if ( event instanceof HttpResponse ) {
// valid response // Do some processing
}
}, err => {
if ( err instanceof HttpErrorResponse ) {
*// Error handler *
}
} );
}
}
…On Tue, Feb 26, 2019 at 11:30 AM Femina ***@***.***> wrote:
how to append custom headers and also params with get request of
@angular/common/http ?
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<#18012 (comment)>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AdzK9TqQmg5BPDgEpumYxmH2Qz1vpHlXks5vRM2PgaJpZM4ORvz3>
.
|
How can I get below format with HttpParams? ?parameters=%7B%22POPID %22:%22 9999991247%22,%22FormType%22:1%7D without encoding |
@ButtonWire, I think you'll need to play with native JavaScript |
similar problem, I am using the interceptor, tried to remove one of the key from the params, it is not getting deleted. I know you can assign a value to read-only object.
|
This issue has been automatically locked due to inactivity. Read more about our automatic conversation locking policy. This action has been performed automatically by a bot. |
I'm submitting a ...
Current behavior
If I follow correctly, we have to do:
whereas the old
Http
service allowed to use a simple object literal (see https://github.com/angular/angular/blob/master/packages/http/src/interfaces.ts#L48):It would be great to be able to do the same.
Expected behavior
Please tell us about your environment
cc @alxhub @IgorMinar
The text was updated successfully, but these errors were encountered: