2016-01-20 203 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
但是,即使上述鏈接中的討論僅在使用綁定對象時注意 注意使用雙向綁定屬性值'='。因此,組件服務和工廠也應該採用同樣的推理。如果您計劃在其他組件範圍和/或父範圍內使用相同的服務或工廠,我建議設置您的父範圍所在的服務/工廠或您想要的服務/工廠所在地。特別是如果你有許多使用相同服務/工廠的組件。你不希望它位於一些很難找到的任意組件模塊中。