Krishna
Krishna

Reputation: 1985

variable passed in constructor of httpInterceptor is not getting assigned to "this" object - angular2-rc4

I have created one http interceptor follow this tutorial.
https://www.illucit.com/blog/2016/03/angular2-http-authentication-interceptor/

Below is my code:

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

        });
    }
}

And below is the code to bootstrap it:

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

If you see the constructor of CustomHttp, I'm injecting object of EventEmitterService. But this object is not getting assigned to "this" object of the class. Due to which I'm not able to use in "interceptor" method.
What wrong I'm doing?

Upvotes: 0

Views: 129

Answers (1)

Krishna
Krishna

Reputation: 1985

I got the root cause of this issue. Posting it here so that it can help others.
There is no mistake in above posted code.
I had added { path: '', pathMatch: 'prefix',redirectTo: 'test'} to my routing. When I removed this default routing option, it started working. SO i think problem is with redirect. When we do redirect, this problem occurs.
Thanks

Upvotes: 0

Related Questions