我有一个有角度的2 webapi应用程序,用户必须登录。我现在正在创建一个startpage
,用户可以在尚未登录时查看其部门的消息。用户可以从内部获取的URL登录并将其设置为其起始页时,应用程序包含一个存储在数据库中并与其部门有关系的令牌。
我使用保护服务来保护StartpageComponent
并能够在允许用户继续前进之前检查令牌。我的路由文件如下所示:
const routes: Routes = [
path: '',
component: MainComponent,
children: [{
path: '',
component: NavigationComponent,
children: [{
{
path: 'messages',
component: MessagesComponent
},
{
path: 'startpage',
canActivate: [TokenGuard],
canActivateChild: [TokenGuard],
component: StartpageComponent
}
}]
}]
]
TokenGuard
调用StartpageService.validateToken
,后者又调用webapi来验证令牌。在StartpageService.validateToken
的{{1}}方法的第一次调用中,TokenGuard
不可用。然而,在第二次调用中,令牌可用。
以下代码来自我的accessToken
和TokenGuard
:
StartpageService
import {StartpageService} from 'startpage.service';
import {Injectable} from '@angular/core';
import {CanActivate, Router,ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateChild} from '@angular/router';
@Injectable()
export class TokenGuard implements CanActivate, CanActivateChild {
constructor(
private startPageService: StartpageService,
private router: Router
) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.startPageService.validateToken();
}
canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.canActivate(route, state);
}
}
:
StartpageService
运行此代码会在我的控制台中生成以下消息:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from "rxjs/Observable";
import { ActivatedRoute, Router, Params} from '@angular/router';
@Injectable()
export class StartpageService {
private accessToken: string;
constructor(
private http: Http,
private activatedRoute: ActivatedRoute,
private router: Router
) {
this.activatedRoute.queryParams.subscribe((params) => {
this.accessToken = params['token'];
console.log(`START SERVICE CONSTRUCTOR TOKEN ${this.accessToken}`);
});
}
public validateToken(): Observable<boolean> {
return this.http.get(`${this.startpaginaUrl}?token=${this.accessToken}`).map(res => {
return <boolean>res.json();
});
}
}
答案 0 :(得分:1)
StartpageService
构造函数。
从ActivatedRouteSnapshot
读取令牌,并将其作为参数传递给validateToken
。
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
let token = route.queryParams['token'];
return this.startPageService.validateToken(token);;
}