Reputation: 1905
I wuold like to understand how to implement the httpClient interceptor in this small example , using Angular5
import { Observable } from 'rxjs/Observable';
import {HttpClient, HttpHeaders} from '@angular/common/http';
//service
logintest(): Observable<any>{
var body = {
"username": "[email protected]",
"password": "Passw0rd",
}
let headers = new HttpHeaders().set('Content-Type','application/x-www-form-urlencoded; charset=utf-8;');
return this.http.post("http://restapiUrl/v1/loginservice", body, {headers: headers});
}
thanks in advance Andrea.
Upvotes: 0
Views: 166
Reputation: 3502
Below example might help you.
Create a .TS
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse }
from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
@Injectable()
export class MyInterceptor implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(req).do(evt => {
if (evt instanceof HttpResponse) {
console.log('---> status:', evt.status);
console.log('---> filter:', req.params.get('filter'));
}
});
}
}
To wire-up our interceptor, let’s provide it in the app module or a feature module using the HTTP_INTERCEPTORS token:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyInterceptor } from './interceptors/my.interceptor';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule {}
Upvotes: 1
Reputation: 3698
You have to implement HttpInterceptor and override intercept:
export class AppInterceptor implements HttpInterceptor {
constructor(){
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
}
}
Upvotes: 0