https://grokonez.com/frontend/angular/angular-6/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:
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:
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { Injectable } from '@angular/core';
import {
HttpEvent, HttpInterceptor, HttpHandler,
HttpRequest, HttpResponse
} from '@angular/common/http';
import { finalize, tap } from 'rxjs/operators';
import { LogService } from './log.service';
@Injectable()
export class LoggingInterceptor implements HttpInterceptor {
constructor(private log: LogService) {}
intercept(req: HttpRequest, next: HttpHandler) {
const started = Date.now();
let ok: string;
// Log - start request
this.log.add("Start request -> " + `${req.method} ${req.urlWithParams}`);
return next.handle(req)
.pipe(
tap(
// Success Path
event => ok = event instanceof HttpResponse ? 'succeeded' : '',
// Fail Path
error => ok = 'failed'
),
// Log when response observable either completes or errors
finalize(() => {
const elapsed = Date.now() - started;
const log = `${req.method} ${req.urlWithParams}
, ${ok} in ${elapsed} ms.`;
// Log - end response
this.log.add("End request: " + log);
})
);
}
}
export const httpInterceptorProviders = [
{ provide: HTTP_INTERCEPTORS, useClass: LoggingInterceptor, multi: true }
];
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,
import { HTTP_INTERCEPTORS } from '@angular/common/http';
...
export const httpInterceptorProviders = [
{ provide: HTTP_INTERCEPTORS, useClass: LoggingInterceptor, multi: true }
];
-> Then add it to the AppModule providers array:
@NgModule({
declarations: [
...
],
imports: [
...
],
providers: [
httpInterceptorProviders
],
bootstrap: [AppComponent]
})
export class AppModule { }
Now you define a simple Angular Http Get request as below:
export class CustomerService {
private customersUrl = 'http://localhost:8080/api/customers'; // URL to web api
private handleError: HandleError;
constructor(
private http: HttpClient,
httpErrorHandler: HttpErrorHandler,
private logService: LogService
) {
this.handleError = httpErrorHandler.createHandleError('CustomerService');
}
getCustomers (): Observable {
const message = "Info -> Function: getCustomers. Url: " + this.customersUrl;
this.logService.add(message);
return this.http.get(this.customersUrl)
.pipe(
retry(3),
catchError(this.handleError('getCustomers', []))
);
}
https://grokonez.com/frontend/angular/angular-6/angular-6-http-interceptor-with-node-js-restapis
Top comments (0)