在一般條款,您需要設備的某種基礎設施來聲明依賴關係並抽象聲明的服務或模塊的實例化。
鑑於角例中的問題,如果你退後一步,並在其上反映,一切都在通過角的angular.module
功能發生。
直觀上,這必須如何「應用程序」和後來的應用程式(指令,服務,控制器)的更小的組件聲明和與底層的依賴注入容器中註冊。畢竟,所有這些需要依賴數組作爲第二個參數:
var injectable3, injectable2, injectable;
injectable = angular.module( 'myApp', [dependency, ..., fn(d1, ...){}]);
injectable2 = injectable.controller('foo', [dependency, ..., fn(d2, ...){}]);
injectable3 = injectable.service( 'bar', [dependency, ..., fn(d3, ...){}]);
這似乎不可思議,但它真的不是。他們都通過某種依賴注入容器進行交談。 loader.js
審視一些核心方法的角度:這是在的意見實際上指出:
/**
* @name angular.bootstrap
* @returns {auto.$injector} Returns the newly created injector for app.
*/
function bootstrap(element, modules, config) {
// (...)
var doBootstrap = function(element, modules, config) {
modules = modules || [];
modules.unshift(['$provide', function ($provide) {
$provide.value('$rootElement', element);
}]);
if (config.debugInfoEnabled) {
modules.push(['$compileProvider', function ($compileProvider) {
$compileProvider.debugInfoEnabled(true);
}]);
}
// (...)
modules.unshift('ng');
var injector = createInjector(modules, config.strictDi);
injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
function bootstrapApply(scope, element, compile, injector) {
scope.$apply(function() {
element.data('$injector', injector);
compile(element)(scope);
});
}]
);
return injector;
};
// (...)
if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
return doBootstrap();
}
// (...)
}
如果不記得,引導方法負責初始化應用程序,如<body ng-app="coffeeShop">
。上面的摘錄說明了爲每個應用程序聲明附加的依賴關係。下一步(createInjector
)將找出在哪裏以及如何創建依賴關係。
所以總結一下,一個方法是聲明供應商,具有一定的定位進行註冊,然後聲明依賴於供應商的模塊,並最終引導了整個事情在以後的某個階段。
我覺得我有我的填充這個星期天的早晨。
我第一句不同意,因爲即使我使用的容器來定位「應用程序」在一個地方,它仍然用作一個服務到位的定位。除了App的預先配置的依賴關係之外,什麼都沒有被注入。如果我要爲該項目添加一個後端(dep,dep,dep,...),我需要從容器中獲取(定位服務)它。我不明白我怎麼可以推廣注入依賴到一個構造函數的過程。感謝您的鏈接。 –
你不應該從容器中獲得'BackEnd',只有在你的情況下是'App'的根類。你用容器註冊'BackEnd',然後在你的對象圖中的某個地方註冊一些類,例如通過構造器注入來依賴'BackEnd',然後容器將注入BackEnd到對象圖中的適當位置。 –