2017-07-27 48 views
4

我知道這已被回答,但我不滿意給出的答案。Angular 4如何在註銷後重定向頁面?

我的問題很簡單,用戶想要註銷。

如果它在需要登錄的頁面上(在auth.guard.ts中設置auth.service.ts)並且用戶註銷,我希望他重定向到主頁。

但是如果他在安全頁面我不想重定向他。

我可以使用AuthGuard,但我不想重新載入頁面,所以沒有:

location.reload() 

什麼是我的選擇嗎?

回答

6
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

當他像這樣註銷到家時,您可以重定向用戶。

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

@Injectable() 

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

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

其餘的,我有點困惑......可以分享你的代碼嗎?

+0

我不想重定向他,如果他是一個不要求進行登錄頁面上。假設我有三頁/家庭/管理員和/內容。如果用戶在/ admin上註銷,我想將他重定向到/ home。如果他從內容註銷,我不想重定向他。隨着你的解決方案,我會將他重定向到任何地方。 – Frenentix

+0

爲authSignOutContent()創建一個函數,並且不重定向...或者傳遞一個參數給你的服務,當param爲true時重定向..可以解決你的問題 –

1

請找到下面的代碼重定向希望它可以幫助

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

    export class LogoutComponant { 
    title = 'Logout'; 


constructor(

    private router: Router, 

) {} 

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

}