我写过(从SO复制!)以下拦截器代码。我想修改传出请求并拦截响应。但是,我注意到响应永远不会被截获。为什么?是因为我使用的是Rxjs
吗?
拦截器代码
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from "@angular/common/http";
import {Injectable} from "@angular/core";
import {Observable} from "rxjs/Observable";
import 'rxjs/add/operator/do';
@Injectable()
export class CustomInterceptor implements HttpInterceptor {
constructor() {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log("outgoing request",request);
request = request.clone({
withCredentials: true
});
console.log("new outgoing request",request);
return next
.handle(request)
.do((ev: HttpEvent<any>) => {
if (ev instanceof HttpResponse) {
console.log('processing response', ev); //I DON'T SEE THIS PRINT
}
});
}
}
我将请求发送到服务器,如下所示
return this.http.post(/*this.API_URL+*/this.SIGNIN_USER_URL,body,httpOptions)
.map(response=>{
console.log('response from backend service',response); //I SEE THIS PRINT
let result= <ServerResponse>response;
console.log("result is "+result.result+' with additional information '+result.additionalInformation)
return result;
})
.catch(this.handleError);
为什么拦截器代码没有被击中?
更新 - app.module.ts
providers: [WebToBackendInterfaceService, //some other provider
{
provide: HTTP_INTERCEPTORS,
useClass: CustomInterceptor , //interceptor provider
multi: true
}],
我在do
和if
之间添加了一个打印件(console.log("got an event",ev)
。我可以在控制台上看到以下消息`有一个事件
{…}
body: Object { result: "success", "additional-info": "found user" }
headers: {…}
lazyInit: function lazyInit()
lazyUpdate: null
normalizedNames: Map
size: 0
<entries>
__proto__: Object { … }
__proto__: Object { has: has(), get: get(), keys: keys(), … }
ok: true
status: 200
statusText: "OK"
type: 4
url: "http://localhost:9000/ws/users/signin"
__proto__: Object { constructor: HttpResponse(), clone: clone() }`
我不知道为什么if语句没有被执行,因为事件似乎是HttpResponse
类型(指__proto__: Object { constructor: HttpResponse(), clone: clone() }
)