Search code examples
angularangular2-services

Use service inside service


I'm trying to add some functionality to Http, when user gets 403 it remove his user information and redirect to login. Example of AuthHttp can be seen below.

@Injectable()
export class AuthHttp {
    constructor(
        private http: Http,
        private router: Router,
        private authService: AuthService
    ) { }

    get(url: string, options?: RequestOptionsArgs): Observable<any> {
        return this.http.get(url, options)
            .catch(this.errorHandler);
    }

    errorHandler(error: any): Observable<any> {
        if (error.status === 403) {
            console.error('TOKEN EXPIRED!');
            this.authService.logout();

            let link = ['/login'];
            this.router.navigate(link);
        }

        return Observable.throw(error);
    }
}

The problem is, I will get the following error:

EXCEPTION: this.authService is undefined

Which I don't know how to get around, since I'm trying to use service inside a service. I added AuthService inside providers like below

providers: [ 
    ...,
    AuthService
]

Router will throw similar error.


Solution

  • It's because of the errorHandler method, and the context of which this refers to. You should bind the function to this when you specify it as the callback

    .catch(this.errorHandler.bind(this));
    

    Or if you make errorHandler an arrow function, this (referring to the service instance) will be maintained

    errorHandler = (error: any): Observable<any> => {