Angular HttpInterceptor 不工作
Angular HttpInterceptor does not work
我想实现一个 HttpInterceptor,但不知何故,它什么也没做。
自定义服务实施 HttpInterceptor
:
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse} from '@angular/common/http';
import {AuthenticationService} from "./authentication.service";
import {Observable} from "rxjs/Observable";
@Injectable()
export class HttpInterceptorService implements HttpInterceptor {
constructor(private auth: AuthenticationService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log("INTERCEPTED!!");
const authHeader = this.auth.getAuthorizationHeader();
const authReq = req.clone({setHeaders: {Authorization: authHeader}});
return next.handle(authReq)
.do((event) => {
if (event instanceof HttpResponse) {
console.log(event);
}
}, (error: HttpErrorResponse) => {
console.log(error);
});
}
}
在app.modules.ts
中提供:
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: HttpInterceptorService,
multi: true,
},
AuthenticationService
]
不幸的是,它似乎无所事事。我错过了什么吗?
好的,我知道了。为了执行 get()
调用,我仍然使用 @angular/http
中的 Http
而不是 @angular/common/http
中的 HttpClient
。
现在可以正常使用了。
我想实现一个 HttpInterceptor,但不知何故,它什么也没做。
自定义服务实施 HttpInterceptor
:
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse} from '@angular/common/http';
import {AuthenticationService} from "./authentication.service";
import {Observable} from "rxjs/Observable";
@Injectable()
export class HttpInterceptorService implements HttpInterceptor {
constructor(private auth: AuthenticationService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log("INTERCEPTED!!");
const authHeader = this.auth.getAuthorizationHeader();
const authReq = req.clone({setHeaders: {Authorization: authHeader}});
return next.handle(authReq)
.do((event) => {
if (event instanceof HttpResponse) {
console.log(event);
}
}, (error: HttpErrorResponse) => {
console.log(error);
});
}
}
在app.modules.ts
中提供:
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: HttpInterceptorService,
multi: true,
},
AuthenticationService
]
不幸的是,它似乎无所事事。我错过了什么吗?
好的,我知道了。为了执行 get()
调用,我仍然使用 @angular/http
中的 Http
而不是 @angular/common/http
中的 HttpClient
。
现在可以正常使用了。