Angular - Logout重定向路由

Han*_*pan 11 angularjs

我正在尝试创建一个清除用户会话并将其重定向回根主页的路由.

.config(function config( $routeProvider, $stateProvider ) {

    $routeProvider.
        when('/logout', {resolve: {redirect: function(Session){
            Session.clear();
            return "/home";
        }}});
Run Code Online (Sandbox Code Playgroud)

我在这里做错了,就像打电话一样

$location.path("/logout");
Run Code Online (Sandbox Code Playgroud)

...忽略该功能并重定向回默认路由.我已经尝试将console.log语句添加到函数中以查看它是否被调用.

我是否错误地使用了重定向功能?

小智 19

您是否考虑将注销逻辑放在单独的控制器中?会更清洁,更强大,并使重定向更直接.像这样:

function LogoutController($location) {
    Session.clear();
    $location.path('/home');
}
Run Code Online (Sandbox Code Playgroud)

你的路线是:

when('/logout', {
  template: '', //A template or templateUrl is required by AngularJS, even if your controller always redirects.
  controller: 'LogoutController'
}).    
Run Code Online (Sandbox Code Playgroud)

  • 路由确实需要一个模板,但您可以使用模板将其设置为空:''配置路由时 (4认同)

tof*_*ier 7

我遇到了同样的问题而我所做的是在我的navigationController中创建一个logout函数,当点击该URL时会触发该函数

 <li><a href="" ng-click="logout()" target="_self">Log Out</a></li>
Run Code Online (Sandbox Code Playgroud)

在我的navigationController中:

$scope.logout = function () {
                localStorage.clearAll();
                window.location = '/logout';
            };
Run Code Online (Sandbox Code Playgroud)

我在Angular后面运行ASP.NET,所以我需要浏览器(不是有角度的)路由到/ logout,它在ASP.NET配置中映射(执行一些其他会话清理并重定向到身份验证应用程序)

希望这可以帮助