Angular4: Http -> HttpClient - requestOptions
Asked Answered
L

1

25

So, I am trying to migrate from 'old' http to the new httpClient

with the http client I am using this format in my service:

return this.http.get(environment.api+ '.feed.json', requestOptions)

how do I use this in httpClient?

tried many thiungs... including

return this.http.get(environment.api+ '.feed.json', {params: requestOptions.params})

but getting a type missmatch :(

Loadstar answered 21/8, 2017 at 12:45 Comment(0)
B
22

Try this:

const requestOptions = {
  params: new HttpParams()
};

requestOptions.params.set('foo', 'bar');

this.http.get(environment.api+ '.feed.json', requestOptions );

Here is also the link to the docs describing how to do that with examples for headers and URL Parameters: HttpClient

Brownfield answered 21/8, 2017 at 12:51 Comment(6)
so I cannot use const requestOptions = new RequestOptions(); anymore?Loadstar
no, RequestOptions is part of the @angular/http package - see hereBrownfield
the HttpParams() are really weird.... you cannot do like you did @AndreiMatracaru :/ you have to concatenate like new HttpParams().set('foo', 'bar') otherwise is not working.... and I don't know how to use it if I have many params I need to add but validate first :/Loadstar
@DS_web_developer, in case if you have to do some things with your params and add them after this, you can do something like that: let params = new HttpParams(); params = params.append('foo', 'bar').append('baz', 'qux'); And so on.Semen
How might I use your example to set withCredentials: true?Passant
I defined an interface for RequestOptions in my app based on what Angular expects from the options param. Not sure it's a good solution, if not, it will probably get downvoted here: #56977825Uproarious

© 2022 - 2024 — McMap. All rights reserved.