这是我的Angular TypeScript 拦截器:
export module httpMock_interceptor {
export class Interceptor {
static $inject: string[] = ['$q'];
constructor(public $q: ng.IQService) {}
public request(config: any) {
console.log(this);
}
}
}
这是我的模块,我将其注册为服务。
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');
}]);
当应用程序开始运行时,拦截器构造函数初始化 $ q服务,但是当它转到方法请求我在哪里使用这个关键字,浏览器说此未定义。任何人都可以告诉我我在做错的地方。
这是我编译的拦截器
的代码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 = {}));
模块
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 };
答案 0 :(得分:1)
尝试使用箭头函数将对象的“this”维护为容器对象,或者更确切地说是拦截器:
public request = (config: any) => {
console.log(this);
}
有关背景信息,请参阅:Lambdas并使用'this'@ http://www.typescriptlang.org/Handbook#functions
答案 1 :(得分:0)
根据doc,拦截器应该是一个返回具有request
等属性的对象文字的函数,所以我猜测request
函数是直接调用的,而不是this
1}}对象。