簡體   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