我正在使用Angular应用程序,并尝试检入CanActivate
是否有效,如果有效,请返回true。设置为true时,我需要将其从token
中删除
我已经尝试过这段代码来删除url参数
url
但是它进入了一个无限循环。检查其有效性后如何删除参数?
let url: string = this.router.url.substring(0, this.router.url.indexOf("?"));
this.router.navigateByUrl(url);
`
auth.service.ts
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
let accesstoken: string = next.queryParams.accesstoken;
if (this.authService.IsAuthenticated) {
let user = this.authService.GetUser();
let CurrentDate = new Date();
let date = CurrentDate.getFullYear() + "-" + (CurrentDate.getMonth() + 1) + "-" + CurrentDate.getDate();
if (Date.parse(date) <= Date.parse(user.expire_date)) {
return true;
}
}
else if (!NOU(accesstoken)) { // In case current registered token is not valid, CheckAccess with new token
// this.authService.logout();
this.authService.checkAccess(accesstoken).subscribe(
data => {
if (data === true) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
},
error => {
}
);
}
else {
this.router.navigate(['/login']);
return false;
}
}
reverse-auth.guard.ts
checkAccess(accesstoken: string) {
let Headers = new HttpHeaders();
Headers = Headers.append('AuthenticationToken', accesstoken);
return this.dataService
.post<any>(`${this.authUrl}CheckAccess.json`, null, { headers: Headers })
.pipe(
map(response => {
const authenticated = response.flag;
// login successful
if (authenticated) {
// you can use JSON.parse(localStorage.getItem('user')) statement to get the user information when needed.
const user = new User(response);
localStorage.setItem('user', JSON.stringify(user));
localStorage.setItem('AuthenticationToken', accesstoken);
this.IsAuthenticated = true;
this.authenticationSource.next(true);
// return true to indicate successful login
return authenticated;
}
}),
catchError(conError => {
// return false to indicate failed login response 401
return 'Failed';
})
);
}
app-routing.module.ts
export class ReverseAuthGuard implements CanActivate {
constructor(private router: Router, private authService: AuthService) { }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
if (this.authService.IsAuthenticated) {
let user = this.authService.GetUser();
let CurrentDate = new Date();
let date = CurrentDate.getFullYear() + "-" + (CurrentDate.getMonth() + 1) + "-" + CurrentDate.getDate();
if (Date.parse(date) > Date.parse(user.expire_date)) {
// this.router.navigate(['/']);
return true;
}
this.router.navigate(['/home']);
return false;
}
else {
return true;
}
}
}
答案 0 :(得分:1)
您将陷入无休止的循环,因为您始终会重定向到登录名,并且删除后登录名将检查令牌,这将再次进行重定向。
解决方案是将令牌保存在会话存储中:
else if (!NOU(accesstoken)) {
this.authService.checkAccess(accesstoken).subscribe(
data => {
if (data === true) {
sessionStorage.setItem('access_token', accesstoken);
return true;
} else {
const storageAccessToken = sessionStorage.getItem('access_token');
if (storageAccessToken) {
return true;
}
this.router.navigate(['/login']);
return false;
}
});
} else {
const storageAccessToken = sessionStorage.getItem('access_token');
if (storageAccessToken) {
return true;
}
this.router.navigate(['/login']);
return false;
}
然后您可以毫无问题地进行重定向。要从您的网址中删除它,有很多方法可以执行,就像法塔赫在他的回答中提到的那样。
在对答案进行新的编辑之后,我意识到在没有令牌的情况下,您的代码问题正在重定向。因此,一个基本条件可以解决问题:
if (this.authService.IsAuthenticated) {
let user = this.authService.GetUser();
let CurrentDate = new Date();
let date = CurrentDate.getFullYear() + "-" + (CurrentDate.getMonth() + 1) + "-" + CurrentDate.getDate();
if (Date.parse(date) <= Date.parse(user.expire_date)) {
// check if accesstoken exists
if (accesstoken) {
// redirect only when exists
this.router.navigateByUrl(window.location.pathname);
}
return true;
}
}
else if (!NOU(accesstoken)) { // In case current registered token is not valid, CheckAccess with new token
// this.authService.logout();
this.authService.checkAccess(accesstoken).subscribe(
data => {
if (data === true) {
// check if accesstoken exists
if (accesstoken) {
// redirect only when exists
this.router.navigateByUrl(window.location.pathname);
}
return true;
} else {
this.router.navigate(['/login']);
return false;
}
},
error => {
}
);
}
希望能回答您的问题
答案 1 :(得分:0)
如果我们假设您的查询参数名称是'token',则可以通过那里的名称删除查询参数,并传递空值
this.router.navigate(
['login'], {
queryParams: {
token: null // pass null value to token delete it
},
queryParamsHandling: 'merge'
})