【问题标题】:App/provider circular dependency应用程序/提供者循环依赖
【发布时间】:2014-07-02 07:48:04
【问题描述】:

我想在启动我的 AngularJs 应用程序时使用提供程序来设置一些配置设置,但我希望将应用程序和提供程序放在 2 个单独的文件中。

这就是我现在的样子:

var myApp = angular.module('myApp', []);

myApp.config(function(myServiceProvider) {
....etc.

提供者的定义如下:

angular.module('myApp').provider('myService', function () {
...etc.

如果我先加载应用程序,则提供程序还没有,如果我先加载提供程序,则应用程序还没有。 解决这个问题的最佳方法是什么?

【问题讨论】:

    标签: angularjs provider


    【解决方案1】:

    您的模块定义包括 module 依赖项 - 而不是服务或提供程序。

    应该是:

    var myApp = angular.module('myApp', []);
    

    配置块始终在您的提供程序初始化后执行。不存在循环依赖问题。

    文件 1:定义模块

    angular.module('myApp', []);
    

    文件 2:定义提供者

    angular.module('myApp').provider('myService',function() {...});
    

    文件 3:定义配置块

    angular.module('myApp').config(function(myServiceProvider) { ... });
    

    HTML:

    <script src="/angular.js"></script>
    <script src="/file1.js"></script>
    <script src="/file2.js"></script>
    <script src="/file3.js"></script>
    

    文件的顺序很重要。

    【讨论】:

    • 我的错,但删除它仍然会出现同样的问题,可能是从 myApp.config 需要注入它时
    • 你的模块定义必须有一个空的模块数组作为依赖。否则,您将尝试检索尚未定义的模块。
    • 是的,很抱歉,但还是同样的问题。
    • 啊,我想我知道问题所在了。您不能在同一个文件中调用模块定义和配置方法。提供者尚未定义。
    • @Maarten:注意:在 Angular 版本 1.3.0-beta.8 及更高版本中,情况发生了变化。从那个版本开始,.config() 块在加载服务等之后执行,所以出现的顺序不再起作用。另请参阅此 short demo
    【解决方案2】:

    在您的第一个文件中:

    var myApp = angular.module('myApp', []);
    
    myApp.config(function(myServiceProvider) {
    ....etc.
    

    在你的第二个文件中:

    myApp.provider('myService', function () {
    ...etc.
    

    变量 myApp 是一个全局变量,您可以在您网站的任何地方访问它。 你可以看看Yeoman project,它是一个生成器,可以创建你的 angularjs 应用程序结构并添加许多很酷的功能。

    【讨论】:

    • 这只是将提供程序添加到应用程序的不同语法,但它不能解决我的问题
    猜你喜欢
    • 1970-01-01
    • 2023-03-13
    • 2010-10-28
    • 2022-01-09
    • 2021-09-23
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多