对于Angular 5及以上版本,我们可以使用HttpInterceptor泛化请求和响应操作。
这有助于我们避免重复:
1)通用报头
2)指定响应类型
3)查询请求
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpResponse,
HttpErrorResponse
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {
requestCounter: number = 0;
constructor() {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
responseType: 'json',
setHeaders: {
Authorization: `Bearer token_value`,
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
});
return next.handle(request).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// do stuff with response if you want
}
}, (err: any) => {
if (err instanceof HttpErrorResponse) {
// do stuff with response error if you want
}
});
}
}
我们可以使用这个AuthHttpInterceptor类作为HttpInterceptors的提供者:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app.routing-module';
import { AuthHttpInterceptor } from './services/auth-http.interceptor';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
BrowserAnimationsModule,
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthHttpInterceptor,
multi: true
}
],
exports: [],
bootstrap: [AppComponent]
})
export class AppModule {
}