修改路径

This commit is contained in:
小海
2020-05-16 22:18:45 +08:00
parent abc792a561
commit 42177a7721
683 changed files with 92 additions and 18398 deletions

View File

@@ -0,0 +1,70 @@
import {Injectable} from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router} from '@angular/router';
import {Observable, Observer} from 'rxjs';
import {User} from '../../class/User';
import {GlobalUserService} from '../../services/global-user.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private userService: GlobalUserService, private router: Router) {
// this.userService.refreshUserInfo();
}
userInfo: User;
visitCount: number = 0; // 记录一共走过几次canActivate
private path: string;
private readonly loginPath: string = '/user/login';
private observable: Observable<boolean>;
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
this.path = state.url.indexOf('?') > 0 ? state.url.substr(0, state.url.indexOf('?')) : state.url;
this.visitCount++;
this.observable = new Observable<boolean>(observer => {
if (!this.userInfo) {
this.watchUserInfo(observer);
} else {
this.checkPath(observer);
}
});
return this.observable;
}
watchUserInfo(observer: Observer<boolean>) {
this.userService.watchUserInfo({
complete: null,
error: (err) => {
// 请求重复
if (err.code !== -1) {
observer.next(false);
this.router.navigateByUrl(this.loginPath);
}
},
next: data => {
this.userInfo = data.result;
this.checkPath(observer);
}
})
}
checkPath(observer: Observer<boolean>) {
switch (this.path) {
case '/admin/article':
case '/admin/link':
case '/admin/tag':
case '/admin/update':
case '/admin/user':
case '/admin/visitor':
if (this.userInfo.role !== 'admin') {
observer.next(false)
if (this.visitCount === 1) this.router.navigateByUrl('/admin')
return;
}
}
observer.next(true);
}
}