CustomHttp内访问EventEmitter服务 [英] Access EventEmitter Service inside of CustomHttp
问题描述
我已经创建自定义拦截器:
进口{} EventEmitterService从./EventEmitter.service@Injectable()
出口类CustomHttp扩展HTTP {
构造函数(后端:ConnectionBackend,defaultOptions:RequestOptions,_eventEmitterService:EventEmitterService){
超(后端,defaultOptions);
}
得到(网址:字符串,期权?:RequestOptionsArgs):可观察<应变及GT; {
返回super.get(URL,{标题:interceptorHeaders})赶上((RES)=> {。
如果(res.status === 403){
的console.log(拦截器在这里)
this._eventEmitterService.logout.emit(403);
}
返回Observable.of(RES);
});
}
}
伟大的工程 - 每当我收到从我得到的服务器403响应:
拦截器在这里
在我的控制台。
然而,与注射 EventEmitterService
进入捕捉功能的问题。每当我在它的内部,我不能访问 CustomHttp
- 我只能访问某些观测
,即使当我调试我的构造函数 - 我可以看到 EventEmitterService
已注入
这是我如何注入 EventEmitterService
:
引导程序(App [...,
EventEmitterService,
新的供应商(HTTP,{
useFactory:(后端:XHRBackend,defaultOptions:RequestOptions,_eventEmitterService:EventEmitterService)= GT;新CustomHttp(后端,defaultOptions,_eventEmitterService)
DEPS:[XHRBackend,RequestOptions,EventEmitterService]
}),...]);
也许你只是错过了私人
关键字在 _eventEmitterService <水平/ code>的
CustomHttp
构造函数参数:
出口类CustomHttp扩展HTTP {
构造函数(后端:ConnectionBackend,
defaultOptions:RequestOptions,
私人_eventEmitterService:EventEmitterService){//&下; ----
超(后端,defaultOptions);
}
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]
}),...]);
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);
}
这篇关于CustomHttp内访问EventEmitter服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!