在httpInterceptor的构造函数中传递的变量没有被赋值给"这个"对象 - angular2-rc4

时间:2016-07-14 11:46:31

标签: angular angular2-http

我已经按照本教程创建了一个http拦截器 https://www.illucit.com/blog/2016/03/angular2-http-authentication-interceptor/

以下是我的代码:

import {Injectable} from '@angular/core';
import {Http, Request, RequestOptionsArgs, Response, RequestOptions, ConnectionBackend} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/Rx';
import {EventEmitterService} from '../service/event.emitter';


export class CustomHttp extends Http {
    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private _eventEmitterService: EventEmitterService) {
        super(backend, defaultOptions);
        alert(this._eventEmitterService); //Undefined
        alert(_eventEmitterService); //gives object
    }

    request(url: string | Request, options?: RequestOptionsArgs): 
      Observable<Response> {
        /* CUSTOM CODE GOES HERE SEE EXAMPLE BELOW*/
        return this.intercept(super.request(url , options));
    }

    get(url: string, options?: RequestOptionsArgs): Observable<Response> { 
        console.log('get...');
        return this.intercept(super.get(url, options));
       // super.get(url, options).catch(res=>{alert(res);return Observable.throw(res)})
    }

    intercept(observable: Observable<Response>): Observable<Response> {
         return observable.catch((err, source) => {
            if (err.status  == 401) {
                this._eventEmitterService.get('authenticationFailed').emit('true'); //this._eventEmitterService is undefined
            } 
            return Observable.throw(err);

        });
    }
}

以下是引导它的代码:

bootstrap(AppComponent, [ disableDeprecatedForms(),provideForms(), EventEmitterService, 
    provide(Http, {
        useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, eventEmitterService: EventEmitterService) 
           => new CustomHttp(backend, defaultOptions, eventEmitterService),
        deps: [XHRBackend, RequestOptions, EventEmitterService]
    })
]); 

如果你看到CustomHttp的构造函数,我注入了EventEmitterService的对象。但是这个对象并没有被分配到&#34;这个&#34;班级的对象。因此,我无法使用&#34;拦截器&#34;方法。
我做错了什么?

1 个答案:

答案 0 :(得分:0)

我找到了这个问题的根本原因。在此发布,以便它可以帮助他人 以上发布的代码没有错误 我已将{path:'',pathMatch:'prefix',redirectTo:'test'}添加到我的路由中。当我删除此默认路由选项时,它开始工作。所以我认为问题在于重定向。当我们进行重定向时,会出现此问题 感谢