我的angular2应用程序出现问题,我尝试使用redirectUrl实现authguard,但登录时我总是得到未定义的redirectUrl。
我尝试做的是如果我导航到安全路线,authguard会将我重定向到登录页面,然后在auth.service中设置redirectUrl,然后当我在login.component中点击登录时,它将会从auth.service获取redirectUrl,然后导航到该url。但它总是返回undefined。
每个步骤我都有一个简单的日志。
from auth-guard: /api
from login.component: undefined
AUTH-guard.service.ts
// auth-guard.service.ts
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, 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);
}
private checkLogin(url: string): boolean {
if (this.authService.isSignIn()) {
return true;
}
this.authService.redirectUrl = url;
console.log('from auth-guard: ' + this.authService.redirectUrl);
this.router.navigate(['/login']);
return false;
}
}
login.component.ts
// login.component.ts
import { Component } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { AuthService } from './../shared/auth.service';
import { LoginModel } from './../shared/login.model';
@Component({
selector: 'login',
templateUrl: 'login.component.html'
})
export class LoginComponent {
title: string = "Log in";
model: LoginModel = {
username: "",
password: ""
};
constructor(private authService: AuthService, private router: Router) { }
login(): void {
this.authService.signIn(this.model.username, this.model.password)
.subscribe(() => {
if (this.authService.isSignIn()) {
console.log('from login.component: ' + this.authService.redirectUrl);
let redirect = this.authService.redirectUrl ? this.authService.redirectUrl : '/home';
this.router.navigate([redirect]);
}
});
}
}
auth.service.ts
// auth.service.ts
import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { AuthHttp, tokenNotExpired } from 'angular2-jwt';
import { AppConfig } from './../../../app.config';
@Injectable()
export class AuthService {
public redirectUrl: string;
// more code
public isSignIn(): boolean {
return tokenNotExpired(null, localStorage.getItem('access_token'));
}
// more code
}