Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript interceptor in AngularJS

I'm having problems setting up a request interceptor in AngularJS using TypeScript

The following snippet works, not working variant is commented out. No matter what I inject in the constructor the local variables are undefined in the request method.

module Services
{
    export class AuthInterceptor
    {
        public static Factory(TokenService: Services.ITokenService)
        {
            return new AuthInterceptor(TokenService);
        }

        constructor(private TokenService: Services.ITokenService)
        {
            this.request = (config: ng.IRequestConfig) =>
            {
                config.headers = config.headers || {};
                if(this.TokenService.IsAuthorised())
                    config.headers.Authorization = 'Bearer ' + this.TokenService.Token;
                return config;
            };
        }

        public request: (config: ng.IRequestConfig)=>ng.IRequestConfig;

/* THIS IS NOT WORKING

        public request(config)
        {
                    // this.TokenService is undefined here as well as $window or $q which I tried to inject
            config.headers = config.headers || {};
            if(this.TokenService.Token != "")
                config.headers.Authorization = 'Bearer ' + this.TokenService.Token;
            return config;
        }
*/

    }
}

angular.module("Services")
    .config(($httpProvider: ng.IHttpProvider)=>
    {
        $httpProvider.interceptors.push(Services.AuthInterceptor.Factory);
    });
like image 232
Maxim Balaganskiy Avatar asked Apr 22 '14 06:04

Maxim Balaganskiy


1 Answers

It is because of the wrong this. Solution:

    public request = (config) =>
    {
                // this.TokenService is undefined here as well as $window or $q which I tried to inject
        config.headers = config.headers || {};
        if(this.TokenService.Token != "")
            config.headers.Authorization = 'Bearer ' + this.TokenService.Token;
        return config;
    }

To understand why you need this : https://www.youtube.com/watch?v=tvocUcbCupA&hd=1

like image 148
basarat Avatar answered Oct 13 '22 23:10

basarat