簡體   English   中英

Angular2 CanActivate 導航

[英]Angular2 CanActivate Navigate

我有以下問題。 我制作了一個 CanActivate Guard,如果您已登錄,您可以“轉到”債務組件。 我的問題是當我登錄時我想將用戶重定向到債務組件(因為 RegistrationComponent 是默認的),但它不起作用(實際上我的頁面被阻塞了......而且我不能做任何事情)。 我的 CanActivate 功能

export class AuthGuardService implements CanActivate {

constructor(private router: Router) { }

canActivate(): Promise<boolean>{
    return checkIfAuth().then(() => {
        setLoggedIn(true);
        this.router.navigate(['/debts']); // <- broken :(
        return true;
    }).catch(() => {
        setLoggedIn(false);
        this.router.navigate(['/login']); // <- broken :(
        return false;
    })
  }
}


export function checkIfAuth () {
return new Promise((resolve, reject) => {
    firebase.auth().onAuthStateChanged((user) => {
        if(user){
            return resolve(true);
        }
        else{
            return reject(false);
        }
    })
  })
}

任何我的 app.routing

const APP_ROUTES: Routes = [
    { path: '', redirectTo: '/registration', pathMatch: 'full' },
    {  path: 'registration', component: RegistrationComponent },
    { path: 'login', component: LoginComponent },
    { path: 'myaccount', component: AccountComponent, canActivate: [AuthGuardService]},
    { path: 'debts', component: DebtsComponent, canActivate: [AuthGuardService]}
];

我所做的是一種黑客行為,但它完美無缺:

首先,我確實在我的LoginCompoment路由上設置了一個Guard

{ path: 'login', component: LoginComponent, canActivate: [AuthGuard] }

然后我使用RouterStateSnapshot獲取我的 URL 狀態的單個實例,指示我用戶嘗試訪問的內容。

然后我可以管理 Guard 中的案例:

import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

...

/**
 *  Protects the routes to reach with authentication
 */
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    // Set user authentication state depending on the token's existance
    this.authService.setLoggedInState();
    // Check user authentication state
    if (this.authService.isAuthenticated) {
        // Explicit navigation to '/login' while the user is already authenticated
        if (state.url === '/login') {
            this.router.navigate(['/dashboard']); // Debts for you
        }
        return true;
    } else {
        // Allow route to './login' to get authenticated
        if (state.url === '/login') {
            return true;
        }
        // Explicit navigation to any URL while not being authenticated
        this.router.navigate(['/login']);
        return false;
    }
}

關於快照的文檔鏈接: https : //angular.io/docs/ts/latest/guide/router.html#!# sts = Snapshot:% 20the% 20no-observable% 20alternative

為了使它在您的情況下工作,您只需將setLoggedInState()為您似乎已經擁有的情況。

注意:我將此解決方案稱為HACK,因為您實際上在Login上設置了保護,而即使用戶未通過身份驗證,它仍然允許用戶訪問它。 仍然運作良好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM