如何等待相关模块的运行功能在初始化之前完成 [英] How to wait for dependent modules run function to be completed before initialization

查看:55
本文介绍了如何等待相关模块的运行功能在初始化之前完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试开发一个应用程序,其中一个模块将依赖于第二个模块.在第一个模块运行功能中,我试图使用http从服务器填充一些数据,但由于http调用是异步的,因此第二个模块将在第一个模块完成之前运行,并且结果未定义.下面的代码可以使情况更加清楚

I am trying to develop an app where one module will be dependent on second module. In the first module run function Im trying to fill templatecache with some data from server using http but since http calls are async my second module will run before the first is completed and I get undefined in the result. Below code would make situation more clear

   var app = angular.module('main', []).run(["$templateCache",'$http','$timeout', function ($templateCache,$http,$timeout) {
              $timeout(function () {
                  $templateCache.put('ajay', 'ajay');
              }, 1000);
          }
          ]);

          var secondapp = angular.module('plunker', ['main']);
          secondapp.controller('test', function ($scope, $templateCache, $timeout) {
              // get me undefined i want to wait until module main is finished running run function 
              alert($templateCache.get('ajay'));
          });

推荐答案

拥抱异步性:

 var app = angular.module('main', []).run(["$templateCache",'$http','$timeout', function ($templateCache,$http,$timeout) {
     $templateCache.put('ajay', $http.get("/data/ajay"));
 }
 ]);

 var secondapp = angular.module('plunker', ['main']);
 secondapp.controller('test', function ($scope, $templateCache, $timeout) {
     $templateCache.get('ajay').then(function (data) {
         alert(data);
     });
 });

这篇关于如何等待相关模块的运行功能在初始化之前完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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