在Angular文档中有一个教程:Milestone 5: Route guards。实现此目的的一种可能方式是使用您的AuthGuard来检查您的登录状态并将URL存储在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; }
this.authService.redirectUrl = url;
this.router.navigate(['/login']);
return false;
}
}
AuthService或者你的LoginService
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Router } from '@angular/router';
@Injectable()
export class AuthService {
isLoggedIn: boolean = false;
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) => {
this.isLoggedIn = true;
if (this.redirectUrl) {
this.router.navigate([this.redirectUrl]);
this.redirectUrl = null;
}
}
}
logout(): void {
this.isLoggedIn = false;
}
}
我认为这将让你了解事物是如何工作的,当然你可能需要根据你的代码进行适应。