简体   繁体   中英

ANGULAR5: how to use httpClient interceptor

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": "abc@abc.com",
      "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.

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 {}

You have to implement HttpInterceptor and override intercept:

export class AppInterceptor implements HttpInterceptor {

 constructor(){
 }

 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM