2016-08-23 40 views
0

你好,我有简单的login服务看起来像:angularjs,等待认定结果之前,转到下一个控制器

this.notifyAuthorization = function() { 
    console.log('notifyAuthorization()'); 

    $http({ 
     url: 'app/?cmd=authorization/', 

    }).then(function (response) { console.log('LoginStatusResult: '); console.log(response.data); 
     var data = response.data; 

     if(data.hash !== undefined) { 
      $rootScope.loginStatus= true; 
      hash = data.hash; 
     } 
    }); 
}; 

这里是呼吁服务

app.run(function($rootScope, $location, LoginService) { 
    LoginService.notifyAuthorization(); 
    console.log('notifyAuthorization Finished'); 
}); 

看到LoginStatusResult我看到之前notifyAuthorization Finished 和其他控制器初始化,应该知道LoginStatus所以如何解决这个问题?还是有更好的做法? 感谢

+0

这是因为'notifyAuthorization()'是一个异步函数,这意味着它不会阻塞代码的其余部分,直到它完成。你可以使用** promises **来解决这个问题。查看[$ q服务](https://docs.angularjs.org/api/ng/service/$q)。 – byxor

回答

2

使用promises,其默认给你的$ HTTP功能:

this.notifyAuthorization = function() { 

    return http({ //notice the return inserted here 
     url: 'app/?cmd=authorization/', 

    }).then(function (response) { console.log('LoginStatusResult: '); console.log(response.data); 
     var data = response.data; 

     if(data.hash !== undefined) { 
      $rootScope.loginState = true; 
      hash = data.hash; 
     } 
    }); 
}; 

,并在您app.run正确地使用它:

app.run(function($rootScope, $location, LoginService) {  
    LoginService.notifyAuthorization().then(function(){ 
     $rootScope.authorized = true;; //executed after your $http request... 
    }); 
}); 

,并在您的html代码:

<div ng-controller="myController" ng-if="$root.authorized"> 
    <!-- your inner code.. 

     <p>Pellentesque habitant morbi tristique senectus et netus et     
     malesuada fames ac turpis egestas. Vestibulum tortor quam, 
     feugiat vitae, ultricies eget, tempor sit amet, ante. </p>    
    --> 
</div> 

这样,你的控制器将instantiat只有在.then函数解决后才能编辑

+0

它对我来说也是一样的,因为我需要知道控制器初始化之前的LoginStatus –

+0

然后在你的notifyAuthorization函数中添加一个ng-if变量。详细信息请参阅我的更新答案。 – Luxor001

+0

假设我有一个LoginController,如果'root.authorized'为TRUE,我不需要调用LoginController,默认情况下'root.authorized'是FALSE,所以它会调用LoginController,然后当Result接收到NG -IF它会隐藏控制器在这种情况下我能做些什么? –

相关问题