Angularjs初始化服务 [英] Angularjs Init Service

查看:97
本文介绍了Angularjs初始化服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作AngularJs项目中使用服务调用其中有顶级导航项目的负载从服务器

I'm working on AngularJs project which have top navigation items load from server using a service call

App.service('Menu', function($http){
   return {
       get:function(callback){
           $http.get('api/menu.json').success(function(menuData){
               callback(menuData);
           });
       }
   }
});

我在使用相同的我 BaseController 如下

App.controller('BaseCtrl', function($scope, Menu){
    $scope.menuData = {};
    Menu.get(function(menuData){
        $scope.menuData = menuData;
    });
});

我的菜单看起来空白了一会儿,直到服务呼叫成功,并赋值给 $ scope.menuData 有什么办法渲染视图之前获取相同

My Menu looks blank for a while until the service call succeed and assign the value to the $scope.menuData is there any way to fetch the same before rendering the view.

请让我知道,我可能已经尝试了所有可能的方式来做到这一点,但是毫无效果:(

Please let me know, I might have tried all possible ways to do this, but nothing worked :(

PS:我使用AngularJS v1.2.9

PS: I'm using AngularJS v1.2.9

推荐答案

从你的服务回报承诺,并使用在您的控制器的决心:

Return a promise from your service, and use that in your controller's resolve:

app.service('Menu', function($http) {
    var menuData = null;

    var promise = $http.get('api/menu.json').success(function (data) {
      menuData = data;
    });

  return{
          getMenuPromise: promise,
          getMenuData:function(){
            return menuData;
          }
   };
});

和你的路由定义:

$routeProvider
    .when('/home',{controller:'BaseCtrl',
    templateUrl:'../homeTpl.html',
    resolve:{
      'menuData':function(Menu){
        return Menu.getMenuPromise;
     }
    }})

现在,当 BaseCtrl 被实例化的数据有:

Now when BaseCtrl is instantiated the data is there:

app.controller('BaseCtrl', function($scope,Menu) {
  $scope.menuData = MyService.getMenuData();
});

这篇关于Angularjs初始化服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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