最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular 4 How to redirect page after logout? - Stack Overflow

programmeradmin4浏览0评论

I know this has been answered previously but I'm not satisfied with the answers given.

My problem is simple, the user want to logout.

If it's on a page that required to be login (set in auth.guard.ts with auth.service.ts) and the user logout I want him to be redirected to home.

However if he is on a safe page I don't want to redirected him.

I could use the AuthGuard but I don't want to reload the page, so no:

location.reload()

What's my option ?

I know this has been answered previously but I'm not satisfied with the answers given.

My problem is simple, the user want to logout.

If it's on a page that required to be login (set in auth.guard.ts with auth.service.ts) and the user logout I want him to be redirected to home.

However if he is on a safe page I don't want to redirected him.

I could use the AuthGuard but I don't want to reload the page, so no:

location.reload()

What's my option ?

Share Improve this question edited May 8, 2023 at 16:48 Vega 28.7k28 gold badges120 silver badges145 bronze badges asked Jul 27, 2017 at 16:06 FrennetixFrennetix 3,3795 gold badges16 silver badges23 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 13
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.'
   }
 }

Please find following redirection code hope it helps

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

  export class LogoutComponant {
    title = 'Logout';


constructor(

    private router: Router,

) {}

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

}

you can redirect the user when he logs out to home like this.

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

@Injectable()

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

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

About the rest, I'm bit confused... could share your code?

发布评论

评论列表(0)

  1. 暂无评论