[英]ANGULAR5: how to use httpClient interceptor
I wuold like to understand how to implement the httpClient interceptor in this small example , using Angular5 我很想了解如何在这个小示例中使用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});
}
thanks in advance Andrea. 在此先感谢Andrea。
Below example might help you. 以下示例可能会对您有所帮助。
Create a .TS 创建一个.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: 要连接拦截器,请使用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 {}
You have to implement HttpInterceptor and override intercept: 您必须实现HttpInterceptor并覆盖拦截:
export class AppInterceptor implements HttpInterceptor {
constructor(){
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.