1

Here is my Angular TypeScript Interceptor:

export module httpMock_interceptor {
  export class Interceptor  {
      static $inject: string[] = ['$q'];
      constructor(public $q: ng.IQService) {}
       public request(config: any) {
         console.log(this);
       }
     }
   }

Here is my module where I am registering as service.

   import {httpMock_interceptor as interceptor} from './httpMock.interceptor';
   var httpMock: ng.IModule = angular.module("httpMockTs", []);
   httpMock.service("httpMockInterceptor",interceptor.Interceptor);
   httpMock.config.$inject = ['$httpProvider'];
   httpMock.config(['$httpProvider', function ($httpProvider:  ng.IHttpProvider) {
$httpProvider.interceptors.unshift('httpMockInterceptor');
}]);

When the app starts running, the interceptor constructor initializing the $q service, but when it goes to the method request where I am use this keyword, browser says this is undefined. Can anyone tell me where I am doing the mistake.

And Here is my transpiled code for interceptor

export var httpMock_interceptor;
 (function (httpMock_interceptor) {
   class Interceptor {
    constructor(_q) {
        this._q = _q;
    }
    request(config) {
        console.log(this);
    }
   }
Interceptor.$inject = ['$q'];
httpMock_interceptor.Interceptor = Interceptor;
})(httpMock_interceptor || (httpMock_interceptor = {}));

Module

import { httpMock_interceptor as interceptor } from './httpMock.interceptor';
var httpMock = angular.module("httpMockTs", []);
httpMock.service("httpMockInterceptor", interceptor.Interceptor);
httpMock.config.$inject = ['$httpProvider'];
httpMock.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.unshift('httpMockInterceptor');
}]);
export { httpMock };
1
  • 2
    maybe it helps when you show us the transpiled JavaScript code? Commented Oct 9, 2015 at 14:14

2 Answers 2

1

try using an arrow function that maintains a reference as "this" to the container object or rather interceptor:

public request = (config: any) => {
  console.log(this);
}

For background see: Lambdas and using 'this' @ http://www.typescriptlang.org/Handbook#functions

Sign up to request clarification or add additional context in comments.

Comments

0

According to the doc, the interceptor should be a function that returns an object literal with properties like request, so I would guess the request function is called directly without any this object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.