[英]Angular HttpInterceptor does not work
I'd like to implement a HttpInterceptor, but somehow, it's not doing anything at all. 我想实现HttpInterceptor,但是无论如何,它根本没有做任何事情。
Custom service implementing 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);
});
}
}
Provided in app.modules.ts
: 在
app.modules.ts
提供:
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: HttpInterceptorService,
multi: true,
},
AuthenticationService
]
Unfortunately, it seems to be doing nothing. 不幸的是,它似乎无能为力。 Have I missed something?
我错过了什么吗?
Okay, I found out. 知道了 To perform the
get()
call I still used Http
from @angular/http
instead of HttpClient
from @angular/common/http
. 要执行
get()
调用我仍然使用Http
从@angular/http
,而不是HttpClient
从@angular/common/http
。
Now it works fine. 现在工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.