角度使canActivateGuard异步
问题描述:
我有一个Web应用程序,其中有一个JWT令牌传递给管理服务。此JWT来自查询URL,因为存在来自其他应用程序的重定向。服务中的构造函数检查该URL并为其设置token
值(如果该参数在那里)。角度使canActivateGuard异步
我面临的问题是canActivateGuard过早起火。当这被称为观察到让JWT在服务中还没有解决,所以当警卫被解雇时JWT总是不在那里。
我必须弄明白,为了使这项工作isLoggedIn()
在AdminService有可能成为一个可观察的是听的URL的变化,而在后卫canActivate()
有订阅,但不能使这个工程。
下面的代码是我走到这一步,
// Admin Service
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import 'rxjs/Rx';
import {Router, ActivatedRoute, Params} from '@angular/router';
@Injectable()
export class AdminService {
token: string;
constructor(private activatedRoute: ActivatedRoute) {
activatedRoute.queryParams.subscribe(
(params) => {
console.log('queryParams', params);
if(localStorage.getItem('jwt')) {
this.token = localStorage.getItem('jwt');
}
else if(params['jwt']) {
localStorage.setItem('jwt', params['jwt']);
this.token = params['jwt'];
}
});
}
// Check that JWT is in local storage and valid
isLoggedin() {
return (localStorage.getItem('jwt') !== null && localStorage.getItem('jwt') !== 'undefined');
}
}
// Can Activate guard
// Note that this.authService.isLoggedIn() is called before the set JWT in the service is solved
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private authService: AdminService,
private router: Router
) {
}
canActivate() {
if (this.authService.isLoggedin()) {
console.log('all ok, proceed navigation to routed component')
return true;
}
else {
// start a new navigation to redirect to login page
this.router.navigate(['/unauthorized']);
return false;
}
}
}
答
使用ActivatedRouteSnapshot
和RouterStateSnapshot
您的问题将得到解决,而且你不需要你的服务认购JWT。
下面是我在Angular2应用程序中使用的代码示例。
AUTH-guard.ts
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { AuthCookie } from '../shared/services/auth-cookies-handler';
@Injectable()
export default class AuthGuard implements CanActivate {
constructor(private router: Router, private _authCookie: AuthCookie) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
if (this._authCookie.getAuth()) {
return true;
}
else {
this.router.navigate(['/login']);
return false;
}
}
}
希望这会帮助你。
您是否尝试过使用'snapshot'? 'activatedRoute.snapshot.queryParams'。 – developer033
不知道为什么会改变什么? – greatTeacherOnizuka
*“我正面临的问题是canActivateGuard过早启动,当这被称为获取服务中的JWT的observable尚未解决*”。所以..使用'快照'你不必订阅JWT .. – developer033