合并为一个项目 #14

Merged
xiaohai2271 merged 56 commits from issue11 into master 2020-05-16 22:35:08 +08:00
4 changed files with 23 additions and 10 deletions
Showing only changes of commit b266340ef1 - Show all commits

View File

@@ -33,7 +33,8 @@ export class GlobalUserService {
}
if (this.lastRequestTime && Date.now() - this.lastRequestTime < 1000) {
return {
unsubscribe() {
unsubscribe: () => {
this.userObserverArray.splice(this.userObserverArray.indexOf(observer), 1);
observer.complete();
}
}
@@ -44,7 +45,8 @@ export class GlobalUserService {
// 获取数据
const subscription = this.getUserInfoFromServer();
return {
unsubscribe() {
unsubscribe:()=>{
this.userObserverArray.splice(this.userObserverArray.indexOf(observer), 1);
observer.complete();
subscription.unsubscribe()
}

View File

@@ -9,8 +9,8 @@ export class LocalStorageService {
constructor() {
}
// 1分钟
readonly place = 60 * 1000;
// 30s
readonly place = 30 * 1000;
getToken(): string {
return localStorage.getItem('token');

View File

@@ -8,6 +8,7 @@ const routes: Routes = [
{
path: '',
component: AdminComponent,
canActivate: [AuthGuard],
children: [
{
path: 'article',

View File

@@ -1,5 +1,5 @@
import {Injectable} from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree} from '@angular/router';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router} from '@angular/router';
import {Observable} from 'rxjs';
import {User} from '../../class/User';
import {GlobalUserService} from '../../services/global-user.service';
@@ -9,28 +9,36 @@ import {GlobalUserService} from '../../services/global-user.service';
})
export class AuthGuard implements CanActivate {
constructor(private userService: GlobalUserService) {
constructor(private userService: GlobalUserService, private router: Router) {
userService.watchUserInfo({
complete: () => null,
error: (err) => {
// 未登录 重定向
// 请求重复
console.log(err);
if (err.code !== -1) {
this.userInfo = null;
this.router.navigateByUrl(this.loginPath);
}
},
next: data => {
this.userInfo = data.result
console.log(this.path);
// todo :用户信息更新时 重新判断下path
}
})
}
userInfo: User;
private path: string;
private readonly loginPath: string = '/user/login';
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
const path = state.url.indexOf('?') > 0 ? state.url.substr(0, state.url.indexOf('?')) : state.url;
this.path = path
if (path.split('/')[1] === 'admin' && !this.userInfo) {
this.router.navigateByUrl(this.loginPath);
return false;
}
switch (path) {
case '/admin/article':
case '/admin/category':
@@ -39,7 +47,9 @@ export class AuthGuard implements CanActivate {
case '/admin/update':
case '/admin/user':
case '/admin/visitor':
if (!this.userInfo || this.userInfo.role !== 'admin') return false;
if (this.userInfo.role !== 'admin') {
return false;
}
}
return true;
}