javascript app.run() 中的 AngularJS 承诺
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28609205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS promise in app.run()
提问by Felix_Billon
I'm working on angularJs and typescript project. I have to make synchronous http call and get some data from server before I launch my client app and load UI. I search on internet and see everybody speak about promise, huumm okay why not. So I use promise (make $http call and use $q to return promise) in my app.run(). Maybe I'm missing nothing because this is not working at all. Angular launch app.config(), then app.run(), ... But Angular does not wait app.config() finish before launch app.run(). So my first promise is launch in app.run() and before it resolve Angular try to instantiate controller... I don't want to create new service call httpSynchronous but I haven't any other ideas.
我正在研究 angularJs 和 typescript 项目。在启动客户端应用程序并加载 UI 之前,我必须进行同步 http 调用并从服务器获取一些数据。我在互联网上搜索,看到每个人都在谈论承诺,嗯,好吧,为什么不呢。所以我在 app.run() 中使用了 promise(进行 $http 调用并使用 $q 返回 promise)。也许我什么都没遗漏,因为这根本不起作用。Angular 启动 app.config(),然后是 app.run(),...但 Angular 在启动 app.run() 之前不会等待 app.config() 完成。所以我的第一个承诺是在 app.run() 中启动,在它解决 Angular 之前尝试实例化控制器......我不想创建新的服务调用 httpSynchronous 但我没有任何其他想法。
回答by Thomas Roch
Angular does not support asynchronous actions in .config
and .run
functions. If you want to delay your application, there are 2 ways:
Angular 不支持.config
和.run
函数中的异步操作。如果你想延迟你的申请,有两种方法:
- The first one is to delay your whole application by using angular.bootstrap() to manually start it. But anything you do is outside angular, so you don't have access to anything but vanilla JavaScript.
- The second one is to use the resolve property of your routes. If you use a router like angular route segmentor ui router, you can define a top route / state with a resolve which would be resolved when your application loads (and if you force a full reload of your route).
- 第一个是通过使用 angular.bootstrap() 手动启动它来延迟整个应用程序。但是您所做的任何事情都在 angular 之外,所以除了普通的 JavaScript 之外,您无权访问任何东西。
- 第二个是使用路由的解析属性。如果您使用像angular route segment或ui router 这样的路由器,您可以定义一个顶级路由/状态,并在您的应用程序加载时(如果您强制完全重新加载您的路由)解析该解析。