如何等待运行功能依赖模块动初始化之前完成。 [英] How to wait for dependent modules run function to be completed before initilization

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

问题描述

我想开发一个应用程序,其中一个模块将取决于第二个模块。在第一个模块运行功能我试着去填补templatecache使用HTTP但由于HTTP调用是异步我的第二个模块在运行之前从服务器的一些数据上首先是完成我得到的结果。下面code不确定将使得情况更加清晰

  VAR应用= angular.module('主',[])。运行([$ templateCache,$ HTTP,$超时',函数($ templateCache, $ HTTP,$超时){
              $超时(函数(){
                  $ templateCache.put('阿贾伊','阿杰')​​;
              },1000);
          }
          ]);          VAR secondapp = angular.module('plunker',['主']);
          secondapp.controller(测试,函数($范围,$ templateCache,$超时){
              //让我不确定我要等待,直到模块主要运行run函数结束
              警报($ templateCache.get('阿杰')​​);
          });


解决方案

拥抱异步性:

  VAR应用= angular.module('主',[])。运行([$ templateCache,$ HTTP,$超时',函数($ templateCache, $ HTTP,$超时){
     $ templateCache.put('阿贾伊',$ http.get(/数据/阿贾伊));
 }
 ]); VAR secondapp = angular.module('plunker',['主']);
 secondapp.controller(测试,函数($范围,$ templateCache,$超时){
     $ templateCache.get('阿杰')​​,然后(功能(数据){
         警报(数据);
     });
 });

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 untill module main is finished running run function 
              alert($templateCache.get('ajay'));
          });

解决方案

Embrace asynchronicity:

 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天全站免登陆