Angular 6 Http Interceptor – with Node.js RestAPIs

Angular provides HTTP Interception to inspect and transform HTTP requests from your application to the server. In the tutorial, we show how to build an Angular 6 Http Log Interceptor with Node.js RestAPIs.

Related posts:
Error Handler Angular 6 HttpClient – catchError + retry – with Node.js/Express example

Technologies

  • Angular 6
  • RxJS 6
  • Bootstrap 4
  • Visual Studio Code – version 1.24.0
  • Nodejs – v8.11.3

Angular HTTP Interception

@angular/common/http has a major feature HTTP Interception that helps inspect and transform HTTP requests.

Example Log Interceptor:

The intercept method transforms a request into an Observable.
interceptors inspect the request on the way in and forward the request to the handle() method of the next object.
handle() method transforms an HTTP request into an Observable of HttpEvents which include the server’s response.

What is next object?
-> The next object represents the next interceptor in the chain of interceptors. The final next in the chain is the Angular HttpClient handler.

How to provide the interceptor?
-> Firstly, importing HTTP_INTERCEPTORS, injection token from @angular/common/http,

-> Then add it to the AppModule providers array:

Now you define a simple Angular Http Get request as below:

-> Logs with successful response:

angular-6-httpclient-log-interceptor-example-with-nodejs-backend + log results when successfully

-> Logs when Server die -> failed response:

angular-6-httpclient-log-interceptor-example-with-nodejs-backend + log results when fail

Practice

We create 2 projects:

– Angular project:

angular-6-httpclient-log-interceptor-example-with-nodejs-backend + project structure

– Node.js project:

angular-6-httpclient-log-interceptor-example-with-nodejs-backend + nodejs structure

For both projects {Angular, Node.js}, we re-use sourcecodes of the tutorials ->

Error Handler Angular 6 HttpClient – catchError + retry – with Node.js/Express example

What do we build more in the tutorial?
-> With Angular project, to do list:

  • Create Log Service
  • Create Log Component
  • Implement Log Interceptor
  • Integrate LogService with Customer Service

-> With Node.js RestAPIs, we re-use all the sourcecode in Error Handler Angular 6 HttpClient post.

Create Log Service

/src/app/log.service.ts ->

Create Log Component

src/app/log/log.component.ts ->

src/app/log/log.component.html ->

Implement Log Interceptor

src/app/log-interceptor.ts ->

– Add LogInterceptor to providers array of AppModule:

Integrate LogService with Customer Service

src/app/customer.service.ts ->

SourceCode

Angular-6-Http-Interceptor
Node.js-RestAPIs



By grokonez | August 2, 2018.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*