From f8d3494626b73c3cfec6c86a01b35a47de1d323d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A6=BE=E5=87=A0=E6=B5=B7?= Date: Tue, 19 May 2020 17:44:04 +0800 Subject: [PATCH] =?UTF-8?q?=E7=A7=BB=E9=99=A4=E6=9C=AC=E5=9C=B0=E7=BC=93?= =?UTF-8?q?=E5=AD=98=E7=94=A8=E6=88=B7=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/api/http/http.service.ts | 4 +- src/app/services/global-user.service.ts | 88 +++++++++++-------- src/app/services/local-storage.service.ts | 48 +++++----- .../admin-dashboard.component.ts | 8 +- src/app/view/admin/admin-routing.module.ts | 18 ++-- src/app/view/admin/admin.component.html | 8 +- src/app/view/admin/admin.module.ts | 6 +- src/app/view/admin/auth.guard.ts | 19 ++-- 8 files changed, 113 insertions(+), 86 deletions(-) diff --git a/src/app/api/http/http.service.ts b/src/app/api/http/http.service.ts index 8d85933..a9e4e04 100644 --- a/src/app/api/http/http.service.ts +++ b/src/app/api/http/http.service.ts @@ -59,8 +59,8 @@ export class HttpService { if (tokenFromReps) { this.localStorageService.setToken(tokenFromReps); } - if (o.body.code) { - observer.error(o); + if (o.body.code !== 0) { + observer.error(o.body); if (this.errorDispatch) { this.errorDispatch.errHandler(o.body.code, o.body.msg, request); } diff --git a/src/app/services/global-user.service.ts b/src/app/services/global-user.service.ts index f018438..eabae82 100644 --- a/src/app/services/global-user.service.ts +++ b/src/app/services/global-user.service.ts @@ -1,7 +1,7 @@ import {Injectable} from '@angular/core'; import {LoginReq, User} from '../class/User'; import {ApiService} from '../api/api.service'; -import {Observable, Observer} from 'rxjs'; +import {Observable, Observer, Subscription} from 'rxjs'; import {Response} from '../class/HttpReqAndResp'; import {LocalStorageService} from './local-storage.service'; @@ -15,42 +15,32 @@ export class GlobalUserService { } private lastRequestTime: number; + private userInfo: User = null; // 存储订阅者 private userObserverArray: Observer>[] = []; + private multicastArray: Observer>[] = []; + watchUserInfo(observer: Observer>) { if (this.userObserverArray.indexOf(observer) < 0) this.userObserverArray.push(observer); - const user = this.localStorageService.getUser(); - // 判断本地缓存的用户信息是否符合要求,符合要求返回本地缓存 - if (this.localStorageService.isLogin() && user && !this.localStorageService.checkNeedNet()) { - observer.next(new Response(user)); - return { - unsubscribe() { - observer.complete(); - } + this.multicastArray = [...this.userObserverArray]; + let subscription: Subscription = null; + const unsubscribe = () => { + this.userObserverArray.splice(this.userObserverArray.indexOf(observer), 1); + observer.complete(); + if (subscription) subscription.unsubscribe(); + }; + if (this.lastRequestTime && Date.now() - this.lastRequestTime < 3000) { + if (this.userInfo && this.multicastArray.length) { + this.broadcast() + this.lastRequestTime = Date.now(); } + return {unsubscribe} } - if (this.lastRequestTime && Date.now() - this.lastRequestTime < 500) { - return { - unsubscribe: () => { - this.userObserverArray.splice(this.userObserverArray.indexOf(observer), 1); - observer.complete(); - } - } - } - // 不符合 请求网络数据并更新缓存 - // 向订阅者传数据 - this.lastRequestTime = Date.now(); // 获取数据 - const subscription = this.getUserInfoFromServer(); - return { - unsubscribe: () => { - this.userObserverArray.splice(this.userObserverArray.indexOf(observer), 1); - observer.complete(); - subscription.unsubscribe() - } - } + subscription = this.getUserInfoFromServer(); + return {unsubscribe} } // 刷新用户信息 @@ -59,14 +49,16 @@ export class GlobalUserService { } login(loginReq: LoginReq, observer: Observer>) { + this.multicastArray = [...this.userObserverArray]; const oob = new Observable>(o => observer = o); const subscription = this.apiService.login(loginReq).subscribe({ next: o => { // 登录成功 this.localStorageService.setToken(o.result.token); - this.localStorageService.setUser(o.result); + // this.localStorageService.setUser(o.result); // this.userObserver.next(o); - this.userObserverArray.forEach(ob => ob.next(o)) + this.userInfo = o.result; + this.broadcast() observer.next(o); observer.complete(); }, @@ -84,10 +76,12 @@ export class GlobalUserService { } logout(observer?: Observer>) { + this.userInfo = null; + this.multicastArray = [...this.userObserverArray]; // 如果不需要返回消息也ok this.apiService.logout().subscribe(data => { this.localStorageService.clear(); - this.userObserverArray.forEach(ob => ob.next(new Response(null))) + this.broadcast() if (observer) { observer.next(data); observer.complete(); @@ -101,22 +95,42 @@ export class GlobalUserService { }) } - private getUserInfoFromServer() { + getUserInfoFromServer(observer?: Observer>) { return this.apiService.userInfo().subscribe({ next: o => { - this.localStorageService.setUser(o.result); - this.userObserverArray.forEach(ob => ob.next(o)); + this.lastRequestTime = Date.now(); + this.userInfo = o.result; + // this.localStorageService.setUser(o.result); + this.broadcast() + if (observer) { + observer.next(o); + observer.complete(); + } + // this.requested = false; }, error: err => { // console.debug('登录过期 token错误 等等'); + if (observer) { + observer.error(err); + observer.complete(); + } + if (err.code === -1) { // 请求重复 return } - this.localStorageService.removeToken(); - this.userObserverArray.forEach(ob => ob.next(new Response(null))); - this.userObserverArray.forEach(ob => ob.error && ob.error(err)); + // this.requested = false; + // this.localStorageService.removeToken(); + this.multicastArray.forEach(ob => ob.next(new Response(this.userInfo))) + this.multicastArray.forEach(ob => ob.error(err)) + this.multicastArray.splice(0, this.multicastArray.length); + } }); } + + private broadcast() { + this.multicastArray.forEach(ob => ob.next(new Response(this.userInfo))) + this.multicastArray.splice(0, this.multicastArray.length); + } } diff --git a/src/app/services/local-storage.service.ts b/src/app/services/local-storage.service.ts index 8aba216..996fbc1 100644 --- a/src/app/services/local-storage.service.ts +++ b/src/app/services/local-storage.service.ts @@ -29,21 +29,21 @@ export class LocalStorageService { return this.getToken() != null; } - setUser(user: User) { - // TODO: 简单加个密 - localStorage.setItem('t', new Date().valueOf().toString()); - return localStorage.setItem('user', JSON.stringify(user)); - } - - getUser(): User { - if (!this.checkNeedNet()) { - return JSON.parse(localStorage.getItem('user')); - } - } - - removeUser() { - return localStorage.removeItem('user'); - } + // setUser(user: User) { + // // TODO: 简单加个密 + // localStorage.setItem('t', new Date().valueOf().toString()); + // return localStorage.setItem('user', JSON.stringify(user)); + // } + // + // getUser(): User { + // if (!this.checkNeedNet()) { + // return JSON.parse(localStorage.getItem('user')); + // } + // } + // + // removeUser() { + // return localStorage.removeItem('user'); + // } clear() { localStorage.removeItem('token'); @@ -51,13 +51,13 @@ export class LocalStorageService { return localStorage.removeItem('t'); } - checkNeedNet() { - const t: number = Number.parseInt(localStorage.getItem('t'), 10); - if (isNaN(t) || new Date().valueOf() - t > this.place) { - localStorage.removeItem('t'); - localStorage.removeItem('user'); - return true; - } - return false; - } + // checkNeedNet() { + // const t: number = Number.parseInt(localStorage.getItem('t'), 10); + // if (isNaN(t) || new Date().valueOf() - t > this.place) { + // localStorage.removeItem('t'); + // localStorage.removeItem('user'); + // return true; + // } + // return false; + // } } diff --git a/src/app/view/admin/admin-dashboard/admin-dashboard.component.ts b/src/app/view/admin/admin-dashboard/admin-dashboard.component.ts index a8165d5..cf595bf 100644 --- a/src/app/view/admin/admin-dashboard/admin-dashboard.component.ts +++ b/src/app/view/admin/admin-dashboard/admin-dashboard.component.ts @@ -30,6 +30,7 @@ export class AdminDashboardComponent implements OnInit { dayVisitCount: number = 0; userInfo: User = new User(); + private isRequested: boolean = false; ngOnInit(): void { } @@ -52,13 +53,14 @@ export class AdminDashboardComponent implements OnInit { getUserInfo = () => this.userService.watchUserInfo({ next: data => { this.userInfo = data.result - if (data.result && data.result.role === 'admin') { + if (data.result && data.result.role === 'admin' && !this.isRequested) { this.getLog(); this.getCounts(); + this.isRequested = true; this.getDayVisitCount(); } }, - error: null, - complete: null + error: () => null, + complete: () => null }) } diff --git a/src/app/view/admin/admin-routing.module.ts b/src/app/view/admin/admin-routing.module.ts index bb185eb..3e715e6 100644 --- a/src/app/view/admin/admin-routing.module.ts +++ b/src/app/view/admin/admin-routing.module.ts @@ -8,47 +8,47 @@ const routes: Routes = [ { path: '', component: AdminComponent, - // canActivate: [AuthGuard], + canActivate: [AuthGuard], children: [ { path: 'article', loadChildren: () => import('./admin-article/admin-article.module').then(mod => mod.AdminArticleModule), - canActivate: [AuthGuard] + // canActivate: [AuthGuard] }, { path: 'comment', loadChildren: () => import('./admin-comment/admin-comment.module').then(mod => mod.AdminCommentModule), - canActivate: [AuthGuard] + // canActivate: [AuthGuard] }, { path: 'link', loadChildren: () => import('./admin-link/admin-link.module').then(mod => mod.AdminLinkModule), - canActivate: [AuthGuard] + // canActivate: [AuthGuard] }, { path: 'tag', loadChildren: () => import('./admin-tag/admin-tag.module').then(mod => mod.AdminTagModule), - canActivate: [AuthGuard] + // canActivate: [AuthGuard] }, { path: 'update', loadChildren: () => import('./admin-update/admin-update.module').then(mod => mod.AdminUpdateModule), - canActivate: [AuthGuard] + // canActivate: [AuthGuard] }, { path: 'user', loadChildren: () => import('./admin-user/admin-user.module').then(mod => mod.AdminUserModule), - canActivate: [AuthGuard] + // canActivate: [AuthGuard] }, { path: 'visitor', loadChildren: () => import('./admin-visitor/admin-visitor.module').then(mod => mod.AdminVisitorModule), - canActivate: [AuthGuard] + // canActivate: [AuthGuard] }, { path: '**', loadChildren: () => import('./admin-dashboard/admin-dashboard.module').then(mod => mod.AdminDashboardModule), - canActivate: [AuthGuard] + // canActivate: [AuthGuard] } ] } diff --git a/src/app/view/admin/admin.component.html b/src/app/view/admin/admin.component.html index 8e02ed4..cc635a3 100644 --- a/src/app/view/admin/admin.component.html +++ b/src/app/view/admin/admin.component.html @@ -91,24 +91,24 @@

您最近一次登录是在:

-

{{user.recentlyLandedDate}}

+

{{user&&user.recentlyLandedDate}}

- {{user.email}} + {{user&&user.email}}
- {{user.displayName}} + {{user&&user.displayName}}
- + {{user.desc}} diff --git a/src/app/view/admin/admin.module.ts b/src/app/view/admin/admin.module.ts index 2e49390..fc5a1e8 100644 --- a/src/app/view/admin/admin.module.ts +++ b/src/app/view/admin/admin.module.ts @@ -6,6 +6,7 @@ import {NgZorroAntdModule} from 'ng-zorro-antd'; import {NzSpaceModule} from 'ng-zorro-antd/space'; import {AdminHeaderComponent} from '../../components/admin-header/admin-header.component'; import {ReactiveFormsModule} from '@angular/forms'; +import {AuthGuard} from './auth.guard'; @NgModule({ @@ -18,8 +19,9 @@ import {ReactiveFormsModule} from '@angular/forms'; AdminRoutingModule, NgZorroAntdModule, NzSpaceModule, - ReactiveFormsModule - ] + ReactiveFormsModule, + ], + providers: [AuthGuard] }) export class AdminModule { } diff --git a/src/app/view/admin/auth.guard.ts b/src/app/view/admin/auth.guard.ts index a226411..8ff2032 100644 --- a/src/app/view/admin/auth.guard.ts +++ b/src/app/view/admin/auth.guard.ts @@ -1,5 +1,12 @@ import {Injectable} from '@angular/core'; -import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router} from '@angular/router'; +import { + CanActivate, + ActivatedRouteSnapshot, + RouterStateSnapshot, + UrlTree, + Router, + CanActivateChild +} from '@angular/router'; import {Observable, Observer} from 'rxjs'; import {User} from '../../class/User'; import {GlobalUserService} from '../../services/global-user.service'; @@ -10,7 +17,6 @@ import {GlobalUserService} from '../../services/global-user.service'; export class AuthGuard implements CanActivate { constructor(private userService: GlobalUserService, private router: Router) { - // this.userService.refreshUserInfo(); } userInfo: User; @@ -34,11 +40,12 @@ export class AuthGuard implements CanActivate { watchUserInfo(observer: Observer) { this.userService.watchUserInfo({ - complete: null, + complete: () => null, error: (err) => { // 请求重复 if (err.code !== -1) { observer.next(false); + observer.complete(); this.router.navigateByUrl(this.loginPath); } }, @@ -58,13 +65,15 @@ export class AuthGuard implements CanActivate { case '/admin/update': case '/admin/user': case '/admin/visitor': - if (this.userInfo.role !== 'admin') { - observer.next(false) + if (this.userInfo && this.userInfo.role !== 'admin') { + observer.next(false); + observer.complete(); if (this.visitCount === 1) this.router.navigateByUrl('/admin') return; } } observer.next(true); + observer.complete(); } }