Amit Dube Amit Dube - 1 month ago 14
HTTP Question

Registering onError Callback on RxJS Observable causing same http request to be sent twice in Angular 2

I have created a HTTP Interceptor in Angular 2. The code of the interceptor is below
export class HttpInterceptor extends 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;

}
}


In the intercept function if error callback is registered, browser makes same http requests twice, and when the error callback is removed then event is not fired (which is needed to hide loading indicator).

By error call back I mean this line

error => this.dataSharingService.afterRequest.emit("afterRequestEvent")


in the intercept method.

Answer

It seems the subject is registering subscribe() multiple times. Could you try unsubscribing the observable once the response through observable is returned back? Else, you may go for simpler way of creating a new observable during every intercept() call and return it instead to avoid multiple callbacks being registered.