Angular Interceptor for a BaseHref Path in Services
How to add a common BaseHref path to all service calls of an Angular application
Join the DZone community and get the full member experience.
Join For FreeIn a deployment scenario like a Jakarta EE, Angular services have to add the BaseHref
path to each service call. Angular has the feature of HttpInterceptors that can be used to add the BaseHref
in one class. The HttpInterceptors
can be used to to modify the headers, url, and body of Angular service requests/responses.
The example project that is used is Angular2AndJavaEE. It shows how the current Angular Version and Jakarta EE can be integrated.
Angular Interceptor
The BaseHrefInterceptor intercepts all rest requests/responses of the application. It adds the BaseHref path if deployed on the Jakarta EE server and adds nothing if run with the Angular Cli. If an error happens≤ the error gets logged to the browser and it tries to log it on the server too.
xxxxxxxxxx
@Injectable()
export class BaseHrefInterceptor implements HttpInterceptor {
private defaultReqHeader = new HttpHeaders().set( 'Content-Type', 'application/json' );
constructor(
private platformLocation: PlatformLocation,
private crRestService: CrRestService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const myBaseHref = !this.platformLocation.getBaseHrefFromDOM() || this.platformLocation.getBaseHrefFromDOM().length < 2 ? '//'.split('/') : this.platformLocation.getBaseHrefFromDOM().split('/');
req = req.clone({
headers: this.defaultReqHeader,
url: (myBaseHref[1].length > 0 ? '/'+myBaseHref[1] : '') + req.url,
});
return next.handle(req).pipe(tap(event => event, event => this.handleError(event)));
}
private handleError(event: HttpEvent<any>): HttpEvent<any> {
if(event instanceof HttpErrorResponse) {
const error = <HttpErrorResponse> event;
console.log(`failed: ${error.message}`);
if(error.url.indexOf('crLog') < 0) {
this.crRestService.putCrLogMsg(new CrLogMsgImpl('Error', error.message)).subscribe();
}
}
return event;
}
}
In lines1-2, the BaseHrefInterceptor is defined. It needs to be injectable and to implement the HttpInterceptor interface.
In lines 5-7 is the constructor that needs the injections of the Platformlocation for the BaseHref and the CrRestService to log errors.
Line 9 implements the intercept method of the HttpInterceptor Interface.
In line 10 the platformLocation.getBaseHrefFromDOM() gets split to get the BaseHref part of the path. An example path looks like this: '/carrental-web/de/' in deployment or like this: '/' from the Angular Cli.
In line 11-14 the request gets cloned, the default headers are set and the url gets updated.
In line 15 the request get handled and the method handleError gets called if an error happens.
In line 18-27 the handleError method checks if the event is a HttpErrorResponse logs it to the browser and logs it to the server rest endpoint. If the logging to the server fails the loop is broken after the first attempt.
Registering the BaseHrefInterceptor
The BaseHrefInterceptor needs to be registered in the app.module.ts:
xxxxxxxxxx
NgModule({
declarations: [
AppComponent,
CrlistComponent,
CrdetailComponent,
CrValuesComponent,
CrvaluesdComponent,
CrdateComponent,
NumberSeparatorPipe,
NumberseparatorDirective,
CrrootComponent,
CruploadComponent,
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule,
AppRoutingModule
],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: BaseHrefInterceptor, multi: true },
],
bootstrap: [AppComponent]
})
export class AppModule { }
In line 22, the BaseHrefInterceptor
is registered with Angular. Angular can call multiple HttpInterceptors for each request.
Angular Service calls
The rest service calls in the CrRestService look now much simpler:
getCrTableRows(mietNr: string) : Observable<CrTableRow[]> {
return this.http.get<CrTableRow[]>(`/rest/model/crTable/mietNr/${mietNr}`);
}
putCrLogMsg(crLogMsg: CrLogMsg): Observable<CrLogMsg> {
return this.http.put<CrLogMsg>('/rest/model/crLog', crLogMsg);
}
In lines 1-3 the getCrTableRows
call is made that now only calls the rest endpoint and relies on the interceptor to add the header and the modify the url.
In lines 4-7 the putCrLogMsg
call is made that send log statements to the server, to be able to analyze problems in the frontend. The interceptor takes care of the headers and url.
Conclusion
Angular provides with the Http Interceptors a powerful tool to add headers and modify urls of rest requests/responses in a central place. The Http Interceptors can also be used for token handling and other requirements. The BaseHrefInterceptor is designed to work in the development environment with the Angular Cli and in the production environment on the Jakarta EE server. A big thank you to the Angular Team and Community for providing the framework and the eco system.
Opinions expressed by DZone contributors are their own.
Trending
-
What Is Test Pyramid: Getting Started With Test Automation Pyramid
-
Tomorrow’s Cloud Today: Unpacking the Future of Cloud Computing
-
Building and Deploying Microservices With Spring Boot and Docker
-
Chaining API Requests With API Gateway
Comments