Reputation: 163
I have an API which send data as plain text. I need to pass { responseType:'text'} in the service layer but it's not reaching to the interceptor. How to pass headers & responseType for a particular API so that it reaches to interceptor and based on API URL,can pass header came from service layer ?
Interceptor code-
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
// add authorization header with jwt token if available
console.log("request", request.headers);
const token = this.authenticationService.currentUserValue;
if (token && token.token) {
if (!request.url.includes("testAPI/")) {
const newRequest = request.clone({
setHeaders: {
Authorization: `Bearer ${token.token}`,
}
});
return next.handle(newRequest);
} else {
const newRequest = request.clone({
setHeaders: {
Authorization: `Bearer ${token.token}`,
"Content-Type": "text/plain",
Accept: "text/plain",
responseType: "text",
}
});
return next.handle(newRequest);
}
}
}
}
Service Code-
testFunction(token) {
let headers = new HttpHeaders();
headers = headers.set('Authorization', `Bearer ${token}`);
headers = headers.set("Content-Type", "text/plain");
headers = headers.set('Accept', "text/plain");
return this.apiSrv.get(TEST_API, {headers:headers,responseType:'text'});
}
It works after disabling http interceptor and passing options like below. responseType parameter should be passed separately from header to make it work.
{headers:headers,responseType:'text'}
but i don't want to disable/remove interceptor. When i enable interceptor it either overwrites the headers passed in service or headers are not reaching to the interceptor. i passed headers in testFunction but when i debug it shows.
Pleas guide me . how to make it work ?
Upvotes: 0
Views: 2072
Reputation: 163
I passed headers in interceptor like below & it worked.
const newRequest = request.clone({ setHeaders: { Authorization: Bearer ${token.token}, "Content-Type": "text/plain", Accept: "text/plain" },responseType: "text", });
Upvotes: 1