在CustomHttp中访问EventEmitter服务

时间:2016-03-17 11:42:36

标签: angular angular2-services

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

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响应时,我得到:

Interceptor here

在我的控制台中。

但是,将EventEmitterService注入catch函数会出现问题。每当我在其中时,我都无法访问CustomHttp - 我只能访问某些Observable,即使在我调试构造函数时 - 我可以看到已注入EventEmitterService。 / p>

这就是我注入EventEmitterService的方式:

bootstrap(App,[...,
EventEmitterService,
    new Provider(Http, {
        useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, _eventEmitterService:EventEmitterService) => new CustomHttp(backend, defaultOptions,_eventEmitterService),
        deps: [XHRBackend, RequestOptions,EventEmitterService]
    }),...]);

1 个答案:

答案 0 :(得分:2)

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

export class CustomHttp extends Http {
constructor(backend: ConnectionBackend,
            defaultOptions: RequestOptions,
            private _eventEmitterService:EventEmitterService) { // <----
  super(backend, defaultOptions);
}
相关问题