[英]Angularjs run an XHR request before each routeChange, regardless of the controller
I am working on a new project, and on the first phase, I would like to check if the user has a session with the server by sending an XHR HEAD request to /api/me. 我正在研究一个新项目,在第一阶段,我想通过向/ api / me发送XHR HEAD请求来检查用户是否与服务器进行了会话。
I would like to use the following syntax 我想使用以下语法
$rootScope.$on("$routeChangeStart", function(event, current, previous, rejection){/*...*/})
The problem is that I don't want to rewrite this code per each controller, is there any way to do this in a generic way?, .run?, service(factory), which way is the correct one?. 问题是我不想为每个控制器重写此代码,有没有办法以一种通用的方式来做到这一点?,。run,service(factory),哪种方法才是正确的?
please provide a brief smaple of code as I am a total newbie to this framework. 请提供简短的代码,因为我是该框架的新手。
var app = angular.module('home', []);
var httpConfig = {withCredentials: true};
app.config(function($routeProvider){
$routeProvider.
when('/',
{
template: 'views/home.html',
controller: homeCtrl
}).
when('/login',
{
template: 'views/login.html',
controller: loginCtrl
}).
when('/logout',
{
template: 'views/logout.html',
controller: logoutCtrl
}).
otherwise(
{
template: 'views/home.html',
controller: homeCtrl
})
}).
run(function($rootScope, authUser){
$rootScope.$on('$routeChangeStart', function () {
authUser($rootScope);
})
}).
factory('authUser', function($http, httpConfig){
var promise = $http.head('/users/me', httpConfig);
})
You can try using $routeProvider resolve as below: 您可以尝试使用$ routeProvider解析,如下所示:
app.config(function($routeProvider){
$routeProvider.
when('/',
{
template: 'views/home.html',
controller: homeCtrl,
resolve:{auth:"authUser"}
}).
when('/login',
{
template: 'views/login.html',
controller: loginCtrl ,
resolve:{auth:"authUser"}
}).
when('/logout',
{
template: 'views/logout.html',
controller: logoutCtrl,
resolve:{auth:"authUser"}
})
Also you might need to change your factory function to return the promise: 另外,您可能需要更改工厂功能以返回承诺:
app.factory('authUser', function($http, httpConfig){
return $http.head('/users/me', httpConfig);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.