Reputation: 581
I'm trying to retrieve a custom param from http request in an interceptor. I need this to show or not an error message. I set a custom param in this way:
getTickets(): Observable<Ticket> {
var params = new HttpParams();
params.append('showErrorMessage', 'false');
return this.http.get(Conf.BaseUrl + 'tickets', { params: params });
}
And I try to get the param in my interceptor:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
tap(
(event: HttpEvent<any>) => {
let show = req.params.get('showErrorMessage');
...
}
)
)
}
In req.params there isn't my custom param, so I think this isn't the correct way to set and get request params. Any suggestions? Thanks
EDIT: To avoid confusion I change my question, I hope to be clearer. I should set a param calling a service method and make interceptor able to get this param. Is there a way to do this? Is it possible to 'pass' a parameter from service to interceptor during an http request? I tried to use HttpHeaders and HttpParams but it doesn't work.
SOLVED I found a solution. I don't know the reason but using params variable as HttpParams doesn't work. Instead in this way it works:
getTickets(): Observable<Ticket> {
return this.http.get(Conf.BaseUrl + 'tickets', {
headers: {
showErrorMessage: 'false'
});
}
and in interceptor:
...
tap(
(event: HttpEvent<any>) => {
let show = req.headers.get('showErrorMessage');
...
}
)
...
I get the value setted in http request.
Upvotes: 0
Views: 5642
Reputation: 126
For anyone who is stumbled upon the same issue, we can pass custom params in HttpParams. But we have to remember that HttpParams is an immutable object. With an immutable object, every call to params.append() returns a new object. so, we will have to re-assign the returned new object back to params as shown below,
getTickets(): Observable<Ticket> {
var params = new HttpParams();
// Notice that I am re-assigning the params object
params = params.append('showErrorMessage', 'false');
return this.http.get(Conf.BaseUrl + 'tickets', { params: params });
}
And in the interceptor, we can access the value as such
req.params.get('showErrorMessage')
Upvotes: 1
Reputation: 178
Your code looks OK. This didn't work because HttpParams
is immutable and you lost result of append()
. So instead of
params.append('showErrorMessage', 'false');
you should've done
params = params.append('showErrorMessage', 'false');
Or in one line var params = new HttpParams().append('showErrorMessage', 'false');
P.S. I know this is a year old question but I lost an hour on this trying to prove I'm not insane and now search got me to this question with still no answer.
Upvotes: 0
Reputation: 1108
actually you can get it by calling it directly
let show = req.params.get.showErrorMessage;
or
let show = req.params.get.['showErrorMessage'];
you can console.log(req.params)
to see what you have in there. Let me know
Upvotes: 1