繁体   English   中英

ANGULAR5:如何使用httpClient拦截器

[英]ANGULAR5: how to use httpClient interceptor

我很想了解如何在这个小示例中使用Angular5实现httpClient拦截器

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});
}

在此先感谢Andrea。

以下示例可能会对您有所帮助。

创建一个.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'));
      }
    });

  }
}

要连接拦截器,请使用HTTP_INTERCEPTORS令牌在应用程序模块或功能模块中提供它:

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

您必须实现HttpInterceptor并覆盖拦截:

export class AppInterceptor implements HttpInterceptor {

 constructor(){
 }

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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