【问题标题】:Manually bootstrap angular app to create async app initialization手动引导 Angular 应用程序以创建异步应用程序初始化
【发布时间】:2015-07-13 22:10:53
【问题描述】:

我正在尝试手动引导我的 Angular 应用程序,以便异步加载我的应用程序所依赖的一些数据。看到这个article

问题是无论我尝试什么,我都无法使用 angular.injector 访问工厂实例。看到这个plunker

问题是每当我运行这样的代码时:

var Injector = angular.injector(["MyAPP", "ng"]);
var initService = Injector.get("MyService");

我只是收到未知的提供程序错误。

谁能帮我完成这个 plunker 工作,或者指出一个更好的方法来创建一个 Angular 应用程序初始化服务。谢谢,

【问题讨论】:

  • 我认为您发布的内容没有任何问题,但确实没有什么问题。你能提供一个证明这个问题的 plunkr 吗?
  • 你看过官方文档了吗? docs.angularjs.org/guide/bootstrap
  • GPicazo,如果您查看 plunker,您会看到应用程序没有引导,因为 initApp 由于未知的提供程序问题而引发错误。我的问题的根源是如何让注入器服务真正工作并允许访问工厂实例。

标签: javascript angularjs asynchronous bootstrapping


【解决方案1】:

已编辑:已更新以反映我们在 cmets 线程中的讨论。

要设置 initApp() 函数以使用 Promise 异步初始化所需的任何应用程序级服务,包括工厂(如原始 plunker 中定义的那样),您可以让它简单地返回一个 Promise,该 Promise 将在初始注入时解析是完整的;完成后,调用您的 bootstrapApplication() 方法在页面上引导 Angular。

function initApp() {
  return new Promise(function(resolve, reject) {
        var Injector = angular.injector(["ng","plunker"]);
        Injector.invoke(['factoryTwo', function(factoryTwo) { 
          console.log(factoryTwo.test);
          resolve();
        }]);
  });
}


function bootstrapApplication() {
  angular.element(document).ready(function() {
      angular.bootstrap(document, ["plunker"]);
  });
}  

initApp().then(bootstrapApplication);

这是一个分叉 plunker 的链接,上面的代码 sn-p 工作:http://plnkr.co/edit/764AqLZf6rQHwPZ1RAZc?p=preview

【讨论】:

  • 重点是让 initApp 成为一个 Promise 并在 Promise 兑现后引导应用程序。这也不能使它工作,如果您查看控制台,initApp 函数会引发错误。
  • 在引导之前也可以使用角度对象和方法
  • 没错,我还没有打开控制台。这是那个 plunker 的一个分支,initApp 作为 Promise 并加载工厂。还需要在plunker 之前通过注入器加载ng;但这正如您所描述的那样有效:plnkr.co/edit/764AqLZf6rQHwPZ1RAZc?p=preview
  • 嘿,大卫,这个作品真棒。谢谢!不幸的是,它仍然无法在我的主应用程序中运行。我得到 --> [$injector:unpr] 未知提供者:$rootElementProvider
  • 如果您在控制台中单击该链接,它应该会将您带到一个 Angular 错误页面,该页面可能会为您提供更多详细信息。我不知道你还依赖什么。
【解决方案2】:

在插入页面之前,您必须引导加载的 ajax 内容

在将 HTML 字符串插入 DOM 之前,您需要在 HTML 字符串上调用 $compile,以便 Angular 有机会执行绑定。

在你的小提琴中,它看起来像这样。

$("#dynamicContent").html(
  $compile(
    "<button ng-click='count = count + 1' ng-init='count=0'>Increment</button><span>count: {{count}} </span>"
  )(scope)
);

显然,$compile 必须注入您的控制器才能使其工作。

$compile documentation 中了解更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-24
    • 1970-01-01
    • 2016-07-10
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    • 2016-04-12
    相关资源
    最近更新 更多