I have several services in my app that point to different API URLs. Now I need to set different headers to each of these services. My question is now regarding the new interceptors in Angular 4. Is there a possibility to set one interceptor for a specific service? So each service has its specific interceptor?
Hopefully, you guys get my question.
Interceptors are used in conjunction with Java EE managed classes to allow developers to invoke interceptor methods on an associated target class, in conjunction with method invocations or lifecycle events. Common uses of interceptors are logging, auditing, and profiling.
After providing HTTP_INTERCEPTORS we need to inform the class we are going to implement our interceptor into by using useClass. Setting multi to true, makes sure that you can have multiple interceptors in your project.
Interceptor is an API gateway server built for accepting API requests from the client applications and routing them to the appropriate backend services. May it be a single service or multiple services to be called in a single API call, interceptor provides you with the necessary tools to control your API request flow.
In this post, we cover three different Interceptor implementations: Handling HTTP Headers. HTTP Response Formatting. HTTP Error Handling.
TL:DR Answer:
No there is no way. An interceptor is designed to intercept all requests.
Long Answer:
A repository nor a request shouldn't be aware of it's interceptors it could pass. Therefore I don't agree with the solution to mark the request or to check for a specific class.
I rather like more the solution provided here: Example Angular HttpInterceptors
Basically your interceptor has to check a service (mediator pattern) if a specific header should be added.
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log(JSON.stringify(req));
const token: string = this.currentUserService.token;
if (token) {
req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
}
if (!req.headers.has('Content-Type')) {
req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
}
req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
return next.handle(req);
}
It's a good example but be aware that it violates the single responsibility principle (setting multiple headers).
Beside that, my opinion is, that an interceptor is the wrong pattern for your problem. Also I don't see an interceptor as solution for adding a bearer token to a request. That was my use case which brought me here.
Basically I would challange your architecture and to rethink how you create the request. A solution to this problem could be following design:
Abstract-Repository
Has basic methods for get / post / put etc. which returns a HttpRequest.
Has a method called "send" which accepts a HttpRequest as a parameter.
Concret-Repository
Inherits from the abstract repository and extends the basic request function.
So for your use case you have one basic service and every specific / custom service inherits from this particular service which extends the behavior of your request.
Decorator
To take this architecture a step further (as I did) you can create a typescript decorator (not possible in all cases, e.g. when dependency injection is needed) which extends the behavior for all decorated functions. For example adding a specific header. This could look like this:
import { Observable } from 'rxjs/Observable';
import { HttpClient, HttpRequest, HttpEvent } from '@angular/common/http';
import { Injectable } from '@angular/core';
export abstract class BaseRepository<T> {
constructor(protected client: HttpClient) {
}
public createGetRequest(url: string): HttpRequest<T> {
return new HttpRequest("GET", url);
}
public send(request: HttpRequest<T>): Observable<HttpEvent<T>> {
return this.client.request(request);
}
}
@Injectable()
export class NormalServiceRepository extends BaseRepository<any> {
constructor(protected client: HttpClient) {
super(client);
}
public get(url: string): Observable<any> {
const baseRequest = super.createGetRequest(url);
baseRequest.headers.set('Content-Type', 'application/json');
return this.send(baseRequest);
}
}
@Injectable()
export class AuthServiceRepository extends BaseRepository<any> {
constructor(protected client: HttpClient) {
super(client);
}
@AcceptsJson()
@SendsJson()
@ForwardCredentials()
public createGetRequest(url: string): HttpRequest<any> {
return super.createGetRequest(url);
}
public get(url: string): Observable<any> {
const baseRequest = super.createGetRequest(url);
return this.send(baseRequest);
}
}
That should give you a basic picture how the architecture would look like.
More about decorators
TypeScript Decorators
Example Implementations
There actually is a way to have an interceptor for a specific service. Notice the emphasis, because it's not really an implementation of the HttpInterceptor
interface.
TL:DR - jump to examples at the bottom.
The HttpClient
actually only converts the input through all the possible methods into a single structure called HttpRequest
, which is then being passed to an HttpHandler
implementation. That, as the name suggests, is responsible for handling the HTTP requests.
Among HttpHandler
implementations you'd find e.g. HttpInterceptingHandler
(runs the chain of interceptors) or HttpXhrBackend
(inherited through the HttpBackend
class, this handler is the last as it actually sends the XHR request). If you take a look in the source code of the former class, you'll see that it's actually depending on the latter (indirectly, under the HttpBackend
token, HttpXhrBackend
is provided as default implementation). So just like the interceptors, Angular is chaining the handlers through DI, where the last one is the backend executing the request.
What you can do is adding another handler to this chain of handlers, ideally as the first one. For that you will have to define a class extending HttpHandler
, injecting the first implementation of HttpHandler
(by first I mean the implementation, which is provided under the HttpHandler
token) and just call-through in the handle
method after you're done.
At last, since the HTTP client is an Angular service, it may be shared among more services, so you will want to create your own instance to avoid that. The HttpClient constructor requires an HttpHandler
instance, where you pass your own implementation.
See my simple example for handling authentication in such handler:
@Injectable()
export class AuthHandler extends HttpHandler {
constructor(
private readonly auth: AuthService, // custom service providing the auth token
private readonly next: HttpHandler // injects the "default" handler -> HttpInterceptingHandler
) {
super();
}
/** @override */ handle(req: HttpRequest<any>): Observable<HttpEvent<any>> {
// do whatever you need on the request
// because of immutability cloning is required
const clone = req.clone({
setHeaders: { 'Authorization': 'Bearer ' + auth.getToken() }
});
// pass the request to the next handler, eventually ending up in HttpXhrBackend
return this.next.handle(clone);
}
}
And the usage of the handler in that one specific service:
export class HeroService {
protected readonly http: HttpClient;
constructor(auth: AuthHandler) {
// create your own instance with you custom handler
this.http = new HttpClient(auth);
}
async getHero(id: string): Hero {
// every request made through such client goes to the handler for processing
await this.http.get<Hero>(`/api/heroes/${id}`).toPromise();
}
}
This code is working for me on Angular 8.
I hope this helps other lost souls searching for a solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With