当使用Angular1+ES6时,控制器函数中未定义依赖注入,控制器是一个类

Dependency Injections are undefined in controller functions while using Angular1+ ES6, with controller as a class

本文关键字:控制器 一个 注入 未定义 Angular1+ES6 函数 依赖      更新时间:2023-09-26

我使用ES6类来定义我的控制器,所以这是语法,

export class SearchBarController {
    constructor($log) {
        'ngInject';
        $log.debug("Hello");
    }
    textTyped($log){
        $log.debug("change fired.");
    }
} 

视图:

<input type="text" data-ng-model="vm.txt" data-ng-change="vm.textTyped()"/>

因此,构造函数中的"Hello"被记录得很好。但是,typedText()函数中的"change-fired"没有启动,因为显然是未定义的。我如何使类函数textTyped()访问$log服务?

注意:如果我将$log分配给构造函数中的类属性,比如

this.logger = $log;

然后做,

this.logger.debug("Change fired.");

这是有效的。但我不确定这是否是正确的做法。

更新:此外,这种方法将对$log服务的引用公开给绑定到此控制器的视图。这有害吗?

有更好的解决方案吗?

this.logger = $log;

正如你所指出的,这就是方式。由于它是一个对象,因此没有全局范围。

class SearchBarController {
    constructor($scope, $log) {
        this.log = $log;
        // Scope method
        $scope.vm = this;
    }
    textTyped(){
        this.log.debug("change fired.");
    }
}
SearchBarController.$inject = ['$scope', '$log'];

试试这个

如果有人感兴趣,我使用ES6对象破坏:找到了一个更优雅的解决方案

class ABCController {
    constructor($log, $http){
        let vm = this;
        vm.DI = () => ({$log, $http});
    }
    classFn(){
        let vm = this;
        let {$log, $http} = vm.DI();
        //Now use $log and $http straightway
        $log.debug("Testing");
        $http({...}).then();
    }
    classFn2(){
        let vm = this;
        //you can also destructure only the required dependencies in this way
        let {$http} = vm.DI();
    }
}
ABCController.$inject = ['$log', '$http'];

通过这种方式,您不需要编写像vm这样丑陋/令人困惑的代码。DI.log等。同样,通过这种方式,DI在视图中暴露得更少。