2016-10-13 30 views
9

我的應用程序已啓動並運行於Angular 2.1.0。 路由通過路由器防護裝置canActivate進行保護。Angular2 - 成功登錄後重定向到調用url

當將瀏覽器指向像「localhost:8080/customers」這樣的受保護區域時,我會像預期的那樣被重定向到我的登錄頁面。

但成功登錄後,我想重定向到調用URL(在本例中爲「/ customers」)。

處理登錄的代碼看起來像這樣

login(event, username, password) { 
    event.preventDefault(); 
    var success = this.loginService.login(username, password); 
    if (success) { 
    console.log(this.router); 
    this.router.navigate(['']); 
    } else { 
    console.log("Login failed, display error to user"); 
    } 
} 

的問題是,我不知道如何從登錄方法中獲得URL呼叫保持。

我確實發現了一個關於這個問題(和答案),但並沒有真正理解它。 Angular2 Redirect After Login

回答

20

在Angular Docs中有一個很好的例子,Teach Authguard To Authenticate。基本上這個想法是使用你的AuthGuard來檢查你的登錄狀態並把它存儲在你的AuthService上。部分代碼位於上面的網址中。

AuthGuard

import { Injectable }  from '@angular/core'; 
import { 
    CanActivate, Router, 
    ActivatedRouteSnapshot, 
    RouterStateSnapshot 
}       from '@angular/router'; 
import { AuthService }  from './auth.service'; 

@Injectable() 
export class AuthGuard implements CanActivate { 
    constructor(private authService: AuthService, private router: Router) {} 

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { 
    let url: string = state.url; 

    return this.checkLogin(url); 
    } 

    checkLogin(url: string): boolean { 
    if (this.authService.isLoggedIn) { return true; } 

    // Store the attempted URL for redirecting 
    this.authService.redirectUrl = url; 

    // Navigate to the login page with extras 
    this.router.navigate(['/login']); 
    return false; 
    } 
} 

AuthService或您的login服務

import { Injectable } from '@angular/core'; 
import { Http, Response } from '@angular/http'; 
import { Router } from '@angular/router'; 

@Injectable() 
export class AuthService { 
    isLoggedIn: boolean = false;  
    // store the URL so we can redirect after logging in 
    public redirectUrl: string; 

    constructor (
    private http: Http, 
    private router: Router 
) {} 

    login(username, password): Observable<boolean> { 
    const body = { 
     username, 
     password 
    }; 
    return this.http.post('api/login', JSON.stringify(body)).map((res: Response) => { 
     // do whatever with your response 
     this.isLoggedIn = true; 
     if (this.redirectUrl) { 
     this.router.navigate([this.redirectUrl]); 
     this.redirectUrl = null; 
     } 
    } 
    } 

    logout(): void { 
    this.isLoggedIn = false; 
    } 
} 

我認爲這會給一個想法是如何工作的,當然你可能需要去適應你的代碼

+0

我真的需要休息一下。我已經閱讀了angular.io這個頁面很多次,並且錯過了這樣一個明顯的例子... 無論如何,非常感謝,這真的有竅門:) 我確實發現了另一種使用存儲window.location的解決方案。路徑名在同一個mannor中,但您提供的解決方案似乎更像是以角度的方式來做到這一點。 –

+1

@AndersBergquist我知道這種感覺,我總是一遍又一遍地閱讀文檔並學習新東西 –

相關問題