我在Angular 2中创建了一个HTTP拦截器。拦截器的代码如下 导出类HttpInterceptor扩展了Http {
private httpSubject = new Subject<Message>();
httpSubject$ = this.httpSubject.asObservable();
private block : boolean = true;
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private _router: Router, private dataSharingService : DataSharingService) {
super(backend, defaultOptions);
}
post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
this.dataSharingService.beforeRequest.emit("beforeRequestEvent");
return this.intercept(super.post(url, body, this.getRequestOptionArgs(options)));
//return super.post(url, body, this.getRequestOptionArgs(options));
}
put(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
this.dataSharingService.beforeRequest.emit("beforeRequestEvent");
return this.intercept(super.put(url, body, this.getRequestOptionArgs(options)));
}
getRequestOptionArgs(options?: RequestOptionsArgs) : RequestOptionsArgs {
if (options == null) {
options = new RequestOptions();
}
if (options.headers == null) {
options.headers = new Headers();
}
//options.headers.append('Content-Type', 'application/json');
return options;
}
intercept(observable: Observable<Response>): Observable<Response> {
observable.subscribe(
null,
error => this.dataSharingService.afterRequest.emit("afterRequestEvent"),
() => this.dataSharingService.afterRequest.emit("afterRequestEvent")
);
return observable;
}
}
在拦截函数中,如果注册了错误回调,则浏览器会发出两次相同的http请求,并且当删除错误回调时,不会触发事件(这需要隐藏加载指示符)。
错误回叫我的意思是这一行
error => this.dataSharingService.afterRequest.emit("afterRequestEvent")
在拦截方法中。
答案 0 :(得分:0)
似乎主题多次注册subscribe()。一旦通过observable的响应返回,你能尝试取消订阅observable吗?否则,您可以在每次intercept()调用期间更简单地创建新的observable,并返回它以避免多个回调被注册。