简体   繁体   English

在AngularJS中解析之前加载控制器

[英]Controller is loaded before resolve is resolved in AngularJS

My AngularJS resolve doesn't finish before the controller is loaded. 加载控制器之前,我的AngularJS解析未完成。

Background: Say I have a "my profile" page that is requested (user loads website.com/user). 背景:假设我有一个“我的个人资料”页面被请求(用户加载website.com/user)。 I would like to have angular intercept the request and ask for the appropriate data from the server. 我想让角度拦截请求并从服务器请求适当的数据。

The server will reply differently depending on whether the user is logged in/active/etc. 服务器将根据用户是否已登录/活动/等进行不同的答复。 I would like angular to get the data from the server before it loads the template, and before it initiates the appropriate controller. 我希望在加载模板之前以及启动适当的控制器之前从服务器获取数据。 So far it does not. 到目前为止还没有。

App.js code: App.js代码:

.when('/user',
  {
    templateUrl:'/templates/user',
    controller: 'my_profile',
    resolve: {
        some_cute_function_name: function($timeout){
            $timeout(function(){
                console.log('here123');
            },5)
        }
   }

Meanwhile, controller code: 同时,控制器代码:

            console.log('about to update scope');

It turns out that the controller is initiated before the resolve is done. 事实证明,控制器是在解析完成之前启动的。 I know this because the greater the number of seconds before the $timeout is done, the more likely I am to see this: 我知道这是因为$ timeout结束之前的秒数越长,我越有可能看到以下内容:

about to update scope
here123

as opposed to the other way around. 而不是相反。

Is there any way to ensure that the resolve is resolved before the controller is initiated? 有什么方法可以确保在启动控制器之前解决该问题?

Much appreciated! 非常感激!

Your resolver needs to return a promise: 您的解析器需要返回承诺:

  .when('/user',
  {
    templateUrl:'/templates/user',
    controller: 'my_profile',
    resolve: {
        some_cute_function_name: function($timeout){
            return $timeout(function(){
                console.log('here123');
                return { some: 'data' };
            },5);
        }
   }

AngularJS describes resolve as: AngularJS将解析描述为:

"An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises , the router will wait for them all to be resolved or one to be rejected before the controller is instantiated." “应该将可选的依赖关系映射注入到控制器中。 如果这些依赖关系中的任何一个是promise ,路由器将在实例化控制器之前等待所有这些依赖关系被解决或被拒绝。” (emphasis added) (强调)

I take it that unless any of the dependencies are promises, angular won't wait for resolve to finish before instantiating the controller (even if I have operations that take a long time to finish, like a $timeout). 我认为, 除非有任何依赖关系得到保证, 否则 angular不会在实例化控制器之前等待解析完成(即使我完成操作需要很长时间才能完成,例如$ timeout)。

Solution: you have to make sure the resolve involves a promise. 解决方案:您必须确保解决方案涉及承诺。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM