Access EventEmitter Service inside of CustomHttp

廉价感情. 提交于 2019-12-11 12:14:22

问题


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]
    }),...]);

回答1:


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);
}


来源:https://stackoverflow.com/questions/36059564/access-eventemitter-service-inside-of-customhttp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!