DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

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

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
  1. DZone
  2. Coding
  3. Frameworks
  4. Angular Interceptor for a BaseHref Path in Services

Angular Interceptor for a BaseHref Path in Services

How to add a common BaseHref path to all service calls of an Angular application

Sven Loesekann user avatar by
Sven Loesekann
·
Oct. 06, 20 · Tutorial
Like (2)
Save
Tweet
Share
4.31K Views

Join the DZone community and get the full member experience.

Join For Free

In 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.

TypeScript
xxxxxxxxxx
1
28
 
1
@Injectable()
2
export class BaseHrefInterceptor implements HttpInterceptor {
3
    private defaultReqHeader = new HttpHeaders().set( 'Content-Type',               'application/json' );
4
    
5
    constructor(
6
        private platformLocation: PlatformLocation,
7
        private crRestService: CrRestService) {}
8
    
9
 intercept(req: HttpRequest<any>, next: HttpHandler):                           Observable<HttpEvent<any>> {
10
    const myBaseHref = !this.platformLocation.getBaseHrefFromDOM() ||           this.platformLocation.getBaseHrefFromDOM().length < 2 ? '//'.split('/') :           this.platformLocation.getBaseHrefFromDOM().split('/');
11
    req = req.clone({
12
        headers: this.defaultReqHeader,
13
        url: (myBaseHref[1].length > 0 ? '/'+myBaseHref[1] : '') + req.url, 
14
    });     
15
    return next.handle(req).pipe(tap(event => event, event =>                       this.handleError(event)));
16
  }
17
18
  private handleError(event: HttpEvent<any>): HttpEvent<any> {
19
    if(event instanceof HttpErrorResponse) {
20
        const error = <HttpErrorResponse> event;
21
        console.log(`failed: ${error.message}`);
22
        if(error.url.indexOf('crLog') < 0) {
23
            this.crRestService.putCrLogMsg(new CrLogMsgImpl('Error',                        error.message)).subscribe();
24
        }
25
    }
26
    return event;
27
  } 
28
}


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: 

TypeScript
xxxxxxxxxx
1
26
 
1
NgModule({
2
  declarations: [
3
    AppComponent,
4
    CrlistComponent,
5
    CrdetailComponent,
6
    CrValuesComponent,
7
    CrvaluesdComponent,
8
    CrdateComponent,
9
    NumberSeparatorPipe,
10
    NumberseparatorDirective,
11
    CrrootComponent,
12
    CruploadComponent,
13
  ],
14
  imports: [
15
    BrowserModule,
16
    FormsModule,
17
    ReactiveFormsModule,
18
    HttpClientModule,   
19
    AppRoutingModule
20
  ],
21
  providers: [      
22
              { provide: HTTP_INTERCEPTORS, useClass: BaseHrefInterceptor, multi: true },
23
            ],
24
  bootstrap: [AppComponent]
25
})
26
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:

TypeScript
x
 
1
getCrTableRows(mietNr: string) : Observable<CrTableRow[]> {
2
   return this.http.get<CrTableRow[]>(`/rest/model/crTable/mietNr/${mietNr}`);
3
}
4
5
putCrLogMsg(crLogMsg: CrLogMsg): Observable<CrLogMsg> {
6
   return this.http.put<CrLogMsg>('/rest/model/crLog', crLogMsg);
7
}


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.

AngularJS

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

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: