angularjs在哪里开始服务

时间:2014-05-29 20:05:46

标签: angularjs cordova service

我想在app.run函数中的angularjs中启动服务,如下所示:

app.run(function($rootScope, $location, $timeout, MessagesService) {
  if(!MessagesService.isRunning()){
    MessagesService.startService();
  }
}

问题是app.run被调用了两次,即使已经启动了messageservice,它也会运行另一个服务实例... service应该是singleton,所以我不明白发生了什么。或者这可能是一个不好的功能来启动服务?

///编辑 我粘贴整个app.run

app.run(function($rootScope, $location, $timeout, AuthenticationService, FlashService, MessagesService, ContactsService) {


  if(!MessagesService.isRunning()){
    MessagesService.startService();
  }

  if(!ContactsService.isRunning()){
    ContactsService.startService();
  }

  $rootScope.newContactReq = 0;
  $rootScope.newMsgCount = 0;
  var routesThatNotRequireAuth = ['/login','/register'];

  $rootScope.$on('$routeChangeStart', function(event, next, current) {
    if(!_(routesThatNotRequireAuth).contains($location.path())) {
      if(!AuthenticationService.isLoggedIn()){
        $location.path('/login');
        FlashService.show("Please log in to continue.");
      }
    }
  });

  $rootScope.$watch(function() { 
    return $location.path(); 
  },
  function(a){  
    if(!AuthenticationService.isLoggedIn()) {
      $rootScope.isUserAuth = 0;
    }
    else{
      $rootScope.isUserAuth = 1;
    }
  });


});

即使我做了像

这样的事情
if($rootScope.service === undefined)
$rootScope.service = 1;

它比第二次运行app.run而$ rootScope.service再次未定义...

0 个答案:

没有答案