访问 CustomHttp 内部的 EventEmitter 服务 [英] Access EventEmitter Service inside of CustomHttp

查看:13
本文介绍了访问 CustomHttp 内部的 EventEmitter 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为所有 Http 请求创建了自定义拦截器:

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

效果很好 - 每当我收到来自服务器的 403 响应时:

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

Interceptor here

在我的控制台中.

但是,将 EventEmitterService 注入 catch 函数存在问题.每当我在其中时,我都无法访问 CustomHttp - 我只能访问一些 Observable,即使在调试构造函数时 - 我可以看到 EventEmitterService 已注入.

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.

这就是我注入 EventEmitterService 的方式:

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

推荐答案

也许你只是错过了 _eventEmitterService 参数级别的 private 关键字CustomHttp 构造函数:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆