【问题标题】:Dependency Injections are undefined in controller functions while using Angular1+ ES6, with controller as a class使用 Angular 6 时,控制器函数中未定义依赖注入,控制器作为类
【发布时间】:2016-07-15 03:24:05
【问题描述】:

我正在使用 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() 函数中的“更改触发”没有触发,因为显然未定义如何让我的类函数 textTyped() 访问 $log 服务?

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

this.logger = $log;

然后做,

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

这行得通。但我不确定这是否是正确的方法。

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

有没有更好的解决方案?

【问题讨论】:

  • this.logger = $logrecommended approach
  • 好的,谢谢。但是不会将它添加到 'this' 中直接暴露给 viewModel/$scope 吗?

标签: javascript angularjs dependency-injection ecmascript-6


【解决方案1】:
this.logger = $log;

正如你所指出的,就是这样。 因为它是一个对象,所以没有全局范围。

【讨论】:

  • 但是不会把它添加到'this'中直接暴露给viewModel/$scope吗?
【解决方案2】:
class SearchBarController {
    constructor($scope, $log) {
        this.log = $log;

        // Scope method
        $scope.vm = this;
    }

    textTyped(){
        this.log.debug("change fired.");
    }
}

SearchBarController.$inject = ['$scope', '$log'];

这样试试

【讨论】:

  • 这种方法将这个对 $log 服务的引用暴露给绑定到这个控制器的视图。这有害吗?我可以简单地在视图中执行 {{ controllerAs.log.debug("Abc") }}。日志没问题,但如果其他更关键的服务像这样暴露出来怎么办?
【解决方案3】:

如果有人感兴趣,我使用 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 在视图中的暴露更少。

【讨论】:

    猜你喜欢
    • 2017-04-08
    • 1970-01-01
    • 2015-04-02
    • 1970-01-01
    • 2016-02-01
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 2015-12-10
    相关资源
    最近更新 更多