只有运行初始化后,控制器是AngularJS完成 [英] Run controllers only after initialization is complete in AngularJS

查看:189
本文介绍了只有运行初始化后,控制器是AngularJS完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有需要之前我AngularJS应用程序执行任何控制器加载一些全局数据(即决心AngularJS全球依赖)。

I have some global data that needs to be loaded before any controller is executed in my AngularJS application (i.e. resolve dependencies globally in AngularJS).

例如,我有一个 UserService 与确实到后端服务器的请求 getCurrentUser()方法为了获取有关当前认证的用户数据。我有一个控制器,以便启动另一个请求(例如加载用户的平衡)需要这些数据。

For example, I have a UserService with the getCurrentUser() method which does a request to the backend server in order to get data about the currently authenticated user. And I have a controller that needs this data in order to launch yet another request (for example to load user's balance).

我怎样才能做到这一点?

How can I achieve that?

推荐答案

请考虑使用在«<指定的方法href=\"https://blog.mariusschulz.com/2014/10/22/asynchronously-bootstrapping-angularjs-applications-with-server-side-data\"相对=nofollow>异步自举有可能的话,服务器端数据»文章AngularJS应用程序

Update

Please consider using method specified in the «Asynchronously Bootstrapping AngularJS Applications with Server-Side Data» article if possible.

您可以使用href=\"https://github.com/philippd/angular-deferred-bootstrap\" rel=\"nofollow\">的模块来实现,现在!

You can use the angular-deferred-bootstrap module to achieve that now!

我不知道这个答案的正确性了,你仍然可以使用的想法,但一定要与你的实际code正确测试它。我会尽量保持这个答案是最新与从不技术。

I'm not sure about validity of this answer anymore, you can still use the ideas, but be sure to properly test it with your actual code. I will try to keep this answer up to date with never technologies.

有几种方法可以异步应用程序初始化的问题。

There are several approaches to the problem of asynchronous application initialization.

当它涉及到一个控制器调用之前必须先解决数据 - 你可以很容易地使用决心的选项 ngRoute $ routeProvider 。然而,当你需要加载一些全局数据之前,任何控制器被称为 - 你不得不即兴

When it comes to data that must be resolved before a single controller is called - you can easily use resolve option of ngRoute's $routeProvider. However, when you need some global data to be loaded before ANY controller is called - you have to improvise.

我试图收集这个答案的所有可能的解决方案。我为他们提供在preference的顺序。

I've tried to collect all possible solutions in this answer. I'm providing them in the order of preference.

在使用 UI路由器的而不是本地 ngRoute 您可以创建一个抽象根状态,并解决它的所有数据,子状态被激活了。

When using ui-router instead of native ngRoute you can create an abstract root state and resolve all data in it, before sub-states are activated.

我会建议使用这种方法。 UI路由器提供了很多附加功能,包括分层次解决依赖能力,深受开发者社区所接受。

I would recommend to use this approach. ui-router provides a lot of additional features including ability to resolve dependencies hierarchically and is well accepted by the developer community.

module.config(function($urlRouterProvider, stateHelperProvider) {
    $urlRouterProvider.otherwise('/404');
    stateHelperProvider.setNestedState({
        name: 'root',
        template: '<ui-view/>',
        abstract: true,
        resolve: {
            user: function(UserService) {
                // getCurrentUser() returns promise that will be resolved
                // by ui-router before nested states are activated.
                return UserService.getCurrentUser();
            }
        },
        children: [{
            name: 'index',
            url: '/',
            templateUrl: '/partials/index'
        }, {
            name: 'not-found',
            url: '/404',
            templateUrl: '/partials/404'
        }, {
            name: 'balance',
            url: '/balance',
            templateUrl: '/partials/balance',
            resolve: {
                balance: function(UserService, user) {
                    // Using data resolved in parent state.
                    return UserService.getBalanceByAccountId(user.accountId);
                }
            }
        }]
    });
});

的<一个href=\"https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views#statehelper-module\"相对=nofollow> stateHelper 将大大有助于使用抽象根范围方法时,减少code。

The stateHelper will help greatly to reduce the code when using abstract root scope approach.

根范围被定义为抽象所以不能直接激活,它没有任何的URL

Root scope is defined as abstract so can not be activated directly and it has no URL.

模板:'&LT; UI画面/&GT; 需要嵌套的意见正确地显示

template: '<ui-view/>' is required for nested views to be properly rendered.

您可以做出承诺,并把它们添加到 $ rootScope 你的根控制器,即在的run()功能。

You can make promises and add them to the $rootScope inside of your root controller, i.e. run() function.

我创建了一个普拉克验证这个想法:
http://plnkr.co/edit/gpguG5Y2S4KOz1KOKzXe?p=$p$pview

I've created a Plunk to demonstrate the idea: http://plnkr.co/edit/gpguG5Y2S4KOz1KOKzXe?p=preview

这是一个完美的解决方案的工作,但是,它的腌code和使它更难使用和理解(回调地狱)。我会推荐它只有第一种方式是不是为你工作。

This is a perfectly working solution, however, it bloats the code and makes it harder to use and understand (callback hell). I would recommend it only if the first approach is not working for you.

您可以直接包含所有初始化数据到服务器上生成的HTML页面,并从应用程序访问它。

You can include all initialization data directly to the HTML page generated on the server and access it from your application.

考虑这个例子:

<html>

<body>

    <script src="application.js"></script>
    <script type="text/javascript">
        application.init({
            // Pass your data here.
            userData: { ... }
        });
    </script>

</body>

</html>

你还可以在自定义的的init()方法手动引导AngularJS应用应用对象。

And you can bootstrap AngularJS application manually in the init() method of your custom application object.

我真的不喜欢这种方法,因为我相信Web应用程序的前端和后端应严格分开的。理想情况下,你的前端应该是一个静态的网站(如HTML,CSS和JS的一堆可以通过CDN传递)和后端应该是一个严格的无presentation层的API服务器(即它应该一无所知HTML ,CSS和这样)。然而,这是一个工作的解决方案,如果你可以用应用程序组件之间的紧密集成生活。

I don't really like this approach, as I do believe that frontend and backend of Web application should be highly separated. Ideally, your frontend should be a static website (e.g. bunch of HTML, CSS and JS that can be delivered via CDN) and your backend should be a strictly an API server without a presentation layer (i.e. it should know nothing about HTML, CSS and such). However, it's a working solution if you can live with tight integration between application components.

这篇关于只有运行初始化后,控制器是AngularJS完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆