2016-01-20 205 views
22

这可能听起来是newb,但我一直在关注这个tutorial的angularjs组件。angularjs 1.5组件依赖注入

我是新来的组件和如何注入常量UtilsauthService像我这样的组件?

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

谢谢!

回答

17

你应该能够注入的服务到组件的控制器就像一个独立的控制器:

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

    authService.doAuthRelatedActivities().then(...); 
} 
33

你可以注入到组件控制器的服务是这样的:

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'; 
    } 
+0

在ES6需要将参数分配给本地变量的情况下添加 'class FranchisesController {$ state = {state} { this。$ state = $ state; } addFranchise(){ this。$ state.go('franquicias.agregar'); } }' – elporfirio

+0

你从哪里找到这个?我无法在https://docs.angularjs.org/guide/component上的文档中找到它。干杯 –

+0

@NickWhiu你可以在依赖注入部分找到它 - https://docs.angularjs.org/guide/di – Gondy

6

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

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

    authService.doAuthRelatedActivities().then(...); 
    }, 
] 
0

对于功能的编程风格它采用以下语法式服务能够完成任务:

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
但是,即使上述链接中的讨论仅在使用绑定对象时注意 注意使用双向绑定属性值'='。因此,组件服务和工厂也应该采用同样的推理。如果您计划在其他组件范围和/或父范围内使用相同的服务或工厂,我建议设置您的父范围所在的服务/工厂或您想要的服务/工厂所在地。特别是如果你有许多使用相同服务/工厂的组件。你不希望它位于一些很难找到的任意组件模块中。