34

这可能听起来很新,但我一直在关注 angularjs 组件的本教程

我是组件的新手,如何像这样向我的组件注入常量UtilsauthService组件?

app.component('tlOverallHeader', {
    bindings: {
        data: '='
    },
    templateUrl: 'js/indexTimeline/components/tl_overallHeader/templates/tl_overallHeader.html',
    controller: function() {
        this.ms = 'tlOverallheader!'
    }
})

谢谢!

4

4 回答 4

55

您可以像这样向组件控制器注入服务:

angular.module('app.module')
        .component('test', {
            templateUrl: 'views/someview.html',
            bindings: {
                subject: '='
            },
            controller: ['$scope', 'AppConfig', TestController]
        });

    function TestController(scope, config) {
        scope.something = 'abc';
    }

或像这样:

angular.module('app.module')
        .component('test', {
            templateUrl: 'views/someview.html',
            bindings: {
                subject: '='
            },
            controller: TestController
        });

    TestController.$inject = ['$scope', 'AppConfig']
    function TestController(scope, config) {
        scope.something = 'abc';
    }
于 2016-10-13T15:17:10.427 回答
23

您应该能够像独立控制器一样将服务注入组件的控制器:

controller: function(Utils, authService) {
    this.ms = 'tlOverallheader!'

    authService.doAuthRelatedActivities().then(...);
}
于 2016-01-20T04:17:41.440 回答
12

接受的答案不是缩小安全的。你也可以在这里使用缩小安全的依赖注入符号:

controller: ['Utils', 'authService',
  function(Utils, authService) {
    this.ms = 'tlOverallheader!'

    authService.doAuthRelatedActivities().then(...);
  },
]
于 2017-07-21T18:34:01.403 回答
1

对于使用工厂风格服务的函数式编程,以下语法可以完成工作:

angular.module('myApp')

.component('myComponent', {
    templateUrl: 'myTemplate.html',
    controller: ['myFactory', function(myFactory){
        var thisComponent = this;
        thisComponent.myTemplatemsg = myFactory.myFunc();
    }]
})


.factory('myFactory', [ function(){

    return {
        myFunc: function(){
                    return "This message is from the factory";
                }
    };
}]);     

注意:您为组件设置的相同组件服务/工厂也可以在您的应用程序的其他任何地方注入(因此可访问),包括父范围和其他组件范围。这很强大,但很容易被滥用。因此,建议组件只在自己的范围内修改数据,这样就不会混淆谁在修改什么。有关这方面的更多信息,请参阅 https://docs.angularjs.org/guide/component#component-based-application-architecture
但是,即使是上述链接中的讨论也仅解决了对双向绑定属性值的谨慎使用'='使用绑定对象时。因此,同样的推理应该适用于组件服务和工厂。如果您计划在其他组件范围和/或父范围中使用相同的服务或工厂,我建议您将服务/工厂设置在您的父范围所在的位置或您的预期服务/工厂集合所在的位置。特别是如果您有许多组件使用相同的服务/工厂。您不希望它位于某个难以找到的任意组件模块中。

于 2017-11-20T03:52:13.130 回答