1

I have created custom interceptor for all Http requests:

import {EventEmitterService} from "./EventEmitter.service";

@Injectable()
export class CustomHttp extends Http {
    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, _eventEmitterService:EventEmitterService) {
        super(backend, defaultOptions);
    }
 get(url: string, options?: RequestOptionsArgs): Observable<Response> {
        return super.get(url,{headers: interceptorHeaders}).catch((res)=>{
            if (res.status === 403){
                console.log("Interceptor here")
                this._eventEmitterService.logout.emit("403");
            }
            return Observable.of(res);
        });
    }
}

Which works great - whenever I am receiving a 403 response from the server I get :

Interceptor here

in my console.

However, there is an issue with injecting EventEmitterService into the catch function. Whenever I am inside of it, I cant access CustomHttp - I only have access to some Observable, even though when I debug my constructor - I can see the EventEmitterService has been injected.

This is how I inject EventEmitterService:

bootstrap(App,[...,
EventEmitterService,
    new Provider(Http, {
        useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, _eventEmitterService:EventEmitterService) => new CustomHttp(backend, defaultOptions,_eventEmitterService),
        deps: [XHRBackend, RequestOptions,EventEmitterService]
    }),...]);
2
  • 1
    Don't use EventEmitter in your services, use Observables directly. Mar 17, 2016 at 11:58
  • Alright. How can I then intercept response with status 403 and notify other component/injectable that this status was received?
    – uksz
    Mar 17, 2016 at 12:00

1 Answer 1

2

Perhaps you just missed the private keyword at the level of the _eventEmitterService parameter of the CustomHttp constructor:

export class CustomHttp extends Http {
constructor(backend: ConnectionBackend,
            defaultOptions: RequestOptions,
            private _eventEmitterService:EventEmitterService) { // <----
  super(backend, defaultOptions);
}
1
  • So easy. I thought that public (default), and private in constructor were only important for TypeScript, not for the compiled javascript.
    – uksz
    Mar 17, 2016 at 12:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.