$rootScope.$on 上的引用“this”为空

Jee*_*Lee 2 angularjs typescript

在我的 Typescript AngularJS 控制器中声明了以下构造函数。

static $inject: Array<string> = [
    '$rootScope',
    'BookingRepository'
];
constructor(
    $rootScope: ng.IRootScopeService,
    bookingRepository: soft.data.BookingRepository
) {
    super();

    this.$rootScope = $rootScope;
    this.$rootScope.$on('accessController_onNavAccessSelected', this.accessController_onNavAccessSelected);

    this.bookingRepository = bookingRepository;
}
Run Code Online (Sandbox Code Playgroud)

但是当 accessController_onNavAccessSelected 被调用时,当我引用“this”时我得到了空值。我期待控制器的实例。

// Listening Events
accessController_onNavAccessSelected(event: ng.IAngularEvent, accessViewModel: soft.data.AccessViewModel): void {
    console.log(this);
}
Run Code Online (Sandbox Code Playgroud)

我错过了什么?或者我如何获得我的控制器实例的引用?

Fal*_*aly 5

使用回调时this 会更改关键字的上下文。

为了防止这种情况,添加.bind(this)

this.$rootScope.$on('accessController_onNavAccessSelected', this.accessController_onNavAccessSelected.bind(this));
Run Code Online (Sandbox Code Playgroud)

或者只使用 ES6 的箭头函数:

this.$rootScope.$on('accessController_onNavAccessSelected', this.accessController_onNavAccessSelected.bind(this));
Run Code Online (Sandbox Code Playgroud)