Angular 4如何在注销后重定向页面?

时间:2017-07-27 16:06:58

标签: angular

我知道以前已经回答了这个问题,但我对所给出的答案并不满意。

我的问题很简单,用户想要注销。

如果它位于需要登录的页面上(使用auth.service.ts在auth.guard.ts中设置)并且用户注销我希望他被重定向到家。

然而如果他在安全页面上,我不想重定向他。

我可以使用AuthGuard,但我不想重新加载页面,所以没有:

location.reload()

我的选择是什么?

3 个答案:

答案 0 :(得分:11)

import { Router } from '@angular/router';
.....

constructor(private router:Router, authService: AuthService){}
  //toastMessagesService: ToastMessagesService){} if you have one
....

onLogOut(){
  authService.logOut(); 

  if (this.router.url==="/admin"){
        //this.toastMessagesService.show("Logged out"); // display a toast style message if you have one :)
        this.router.navigate(["/home"]); //for the case 'the user logout I want him to be redirected to home.'
  }
  else{
   // Stay here or do something
   // for the case 'However if he is on a safe page I don't want to redirected him.'
   }
 }

答案 1 :(得分:2)

请找到以下重定向代码,希望它有所帮助

 import {Component} from '@angular/core';
 import {Router} from '@angular/router';

  export class LogoutComponant {
    title = 'Logout';


constructor(

    private router: Router,

) {}

onLogout() {
    this.router.navigate(['/'])
}

}

答案 2 :(得分:1)

您可以在用户登出家中时重定向用户。

import { Router } from '@angular/router';

@Injectable()

export class AuthService {
    constructor( private _router: Router){}

    authSignOut(){
        localStorage.removeItem('user');
        this._router.navigate(['home']);
    }
}

关于其他人,我有点困惑......可以分享你的代码吗?