我正在做一个angular应用程序,我有两个服务,分别是登录后服务和登录前服务。当我使用这两个守卫时,我的应用程序每隔10分钟就会路由一次,例如,假设我从主页导航到帐户页面,在让应用程序空闲10分钟后,它会刷新自己,并在没有用户输入的情况下路由回主页。我想停止这种行为,这样它就不会自己导航了。
这是我试过的警卫
after-login.service.ts
import { Injectable } from "@angular/core";
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { TokenService } from './token.service';
@Injectable()
export class AfterLoginService implements CanActivate {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
console.log(this.Token.loggedIn());
return this.Token.loggedIn();
}
constructor(private Token: TokenService) { }
}
这是我的before-login.service.ts
import { Injectable } from "@angular/core";
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { TokenService } from './token.service';
@Injectable()
export class BeforeLoginService implements CanActivate {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
return !this.Token.loggedIn();
}
constructor(private Token: TokenService) { }
}
这是我的auth.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { TokenService } from './token.service';
@Injectable()
export class AuthService {
private loggedIn = new BehaviorSubject<boolean>(this.Token.loggedIn());
authStatus = this.loggedIn.asObservable();
changeAuthStatus(value: boolean) {
this.loggedIn.next(value)
}
constructor(private Token: TokenService) {
}
}
token.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class TokenService {
private iss = {
login: 'https://Backend/api/login.php',
signup: 'https://Backend/api/signup.php',
}
constructor() { }
handle(token) {
this.set(token);
}
set(token) {
localStorage.setItem('token', token);
}
get() {
return localStorage.getItem('token');
}
remove() {
localStorage.removeItem('token');
}
isValid() {
const token = this.get();
if (token && 'undefined' != token) {
const payload = this.payload(token);
if (payload) {
//will need to remove >= and use >
return Object.values(this.iss).indexOf(payload.iss) >= -1 ? true
: false;
}
}
return false;
}
payload(token) {
// console.log(token);
const payload = token.split('.')[1];
return this.decode(payload);
}
decode(payload) {
return JSON.parse(atob(payload));
}
loggedIn() {
return this.isValid();
}
}
您可能在令牌服务中编写了一些代码来检查用户是否登录,如果不活动10分钟则清除令牌。