2016-10-13 33 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我知道这种感觉,我总是一遍又一遍地阅读文档并学习新东西 –

相关问题