Browse Source

[新增]摄像头连接后端;定时刷新token

develop
邵佳豪 3 years ago
parent
commit
4617a19121
  1. 4
      angular.json
  2. 3
      src/app/app.module.ts
  3. 7
      src/app/auth.guard.ts
  4. 8
      src/app/http-interceptors/base-interceptor.ts
  5. 12
      src/app/pages/login/login.component.ts
  6. 12
      src/app/service/cache-token.service.ts
  7. 21
      src/app/system-management/host-config/host-config.component.ts
  8. 4
      src/app/system-management/navigation/navigation.component.ts

4
angular.json

@ -46,8 +46,8 @@
"budgets": [ "budgets": [
{ {
"type": "initial", "type": "initial",
"maximumWarning": "500kb", "maximumWarning": "5mb",
"maximumError": "1mb" "maximumError": "5mb"
}, },
{ {
"type": "anyComponentStyle", "type": "anyComponentStyle",

3
src/app/app.module.ts

@ -8,7 +8,6 @@ import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http'; import { HttpClientModule } from '@angular/common/http';
import { httpInterceptorProviders } from './http-interceptors/index' import { httpInterceptorProviders } from './http-interceptors/index'
import { CacheTokenService } from './service/cache-token.service' import { CacheTokenService } from './service/cache-token.service'
import { CookieService } from 'ngx-cookie-service';//cookie插件
import { NzNotificationModule } from 'ng-zorro-antd/notification'; import { NzNotificationModule } from 'ng-zorro-antd/notification';
import { NzMessageModule } from 'ng-zorro-antd/message'; import { NzMessageModule } from 'ng-zorro-antd/message';
import { TreeService } from './service/tree.service'; import { TreeService } from './service/tree.service';
@ -28,7 +27,7 @@ import { CustomReuseStrategy } from './CustomReuseStrategy';
NzNotificationModule, NzNotificationModule,
NzMessageModule NzMessageModule
], ],
providers: [httpInterceptorProviders, CacheTokenService, TreeService, CookieService, providers: [httpInterceptorProviders, CacheTokenService, TreeService,
{ provide: RouteReuseStrategy, useClass: CustomReuseStrategy }], { provide: RouteReuseStrategy, useClass: CustomReuseStrategy }],
bootstrap: [AppComponent] bootstrap: [AppComponent]
}) })

7
src/app/auth.guard.ts

@ -1,14 +1,13 @@
import { Component, OnInit, Inject } from '@angular/core'; import { Component, OnInit, Inject } from '@angular/core';
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { CookieService } from 'ngx-cookie-service';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
export class AuthGuard implements CanActivate { export class AuthGuard implements CanActivate {
constructor(private router: Router,private cookieService: CookieService) { constructor(private router: Router) {
} }
@ -24,7 +23,7 @@ export class AuthGuard implements CanActivate {
checkLogin(): boolean { checkLogin(): boolean {
// console.log('xxxxxxxxxxxx') // console.log('xxxxxxxxxxxx')
// 判断本地有没有token // 判断本地有没有token
const token = this.cookieService.get("token") || sessionStorage.getItem('token'); const token = sessionStorage.getItem('token');
// 如果有token,允许访问 // 如果有token,允许访问
if (token) { return true; } if (token) { return true; }

8
src/app/http-interceptors/base-interceptor.ts

@ -7,7 +7,6 @@ import { throwError } from 'rxjs'
import { catchError } from 'rxjs/operators'; import { catchError } from 'rxjs/operators';
import { Router } from '@angular/router' import { Router } from '@angular/router'
import { CacheTokenService } from '../service/cache-token.service' import { CacheTokenService } from '../service/cache-token.service'
import { CookieService } from 'ngx-cookie-service';
import { NzMessageService } from 'ng-zorro-antd/message'; import { NzMessageService } from 'ng-zorro-antd/message';
//baseurl //baseurl
// const baseurl = 'http://39.106.78.171:8008'; // const baseurl = 'http://39.106.78.171:8008';
@ -15,7 +14,7 @@ import { NzMessageService } from 'ng-zorro-antd/message';
@Injectable() @Injectable()
export class BaseInterceptor implements HttpInterceptor { export class BaseInterceptor implements HttpInterceptor {
constructor(private router: Router, public token: CacheTokenService, private cookieService: CookieService, private message: NzMessageService) { } constructor(private router: Router, public token: CacheTokenService, private message: NzMessageService) { }
intercept(req: any, next: HttpHandler) { intercept(req: any, next: HttpHandler) {
@ -33,7 +32,7 @@ export class BaseInterceptor implements HttpInterceptor {
}); });
if (!req.cancelToken) { if (!req.cancelToken) {
/*获取token*/ /*获取token*/
let token = this.cookieService.get("token") let token = sessionStorage.getItem('token')
/*此处设置额外请求头,token令牌*/ /*此处设置额外请求头,token令牌*/
newReq.headers = newReq.headers =
newReq.headers.set('Authorization', `Bearer ${token}`) newReq.headers.set('Authorization', `Bearer ${token}`)
@ -56,10 +55,7 @@ export class BaseInterceptor implements HttpInterceptor {
if (error.status === 401 || error.status === 614) { if (error.status === 401 || error.status === 614) {
this.token.delete() this.token.delete()
sessionStorage.clear() sessionStorage.clear()
// window.localStorage.clear()
localStorage.removeItem("isautologin") localStorage.removeItem("isautologin")
this.cookieService.set("token", '', new Date(new Date().getTime() + 1), '/')
this.cookieService.set("refreshToken", '', new Date(new Date().getTime() + 1), '/')
this.message.create('error', `用户认证信息过期,请重新登录!`); this.message.create('error', `用户认证信息过期,请重新登录!`);
this.router.navigate(['/login']) this.router.navigate(['/login'])
} }

12
src/app/pages/login/login.component.ts

@ -2,7 +2,6 @@ import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http' import { HttpClient } from '@angular/common/http'
import { Router, ActivatedRoute } from '@angular/router' import { Router, ActivatedRoute } from '@angular/router'
import { CacheTokenService } from '../../service/cache-token.service'//引入服务 import { CacheTokenService } from '../../service/cache-token.service'//引入服务
import { CookieService } from 'ngx-cookie-service';//cookie插件
import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message'; import { NzMessageService } from 'ng-zorro-antd/message';
import { Base64 } from 'js-base64'; import { Base64 } from 'js-base64';
@ -17,7 +16,7 @@ import { NzNotificationService } from 'ng-zorro-antd/notification';
export class LoginComponent implements OnInit { export class LoginComponent implements OnInit {
validateForm!: FormGroup; validateForm!: FormGroup;
constructor(private http: HttpClient, private router: Router, public token: CacheTokenService, private cookieService: CookieService, private fb: FormBuilder, private message: NzMessageService) { } constructor(private http: HttpClient, private router: Router, public token: CacheTokenService, private fb: FormBuilder, private message: NzMessageService) { }
ngOnInit() { ngOnInit() {
this.validateForm = this.fb.group({ this.validateForm = this.fb.group({
@ -107,14 +106,11 @@ export class LoginComponent implements OnInit {
this.autoLogin() this.autoLogin()
sessionStorage.setItem("token", data.token); sessionStorage.setItem("token", data.token);
sessionStorage.setItem("refreshToken", data.refreshToken); sessionStorage.setItem("refreshToken", data.refreshToken);
this.cookieService.set("token", data.token, null, '/');
this.cookieService.set("refreshToken", data.refreshToken, null, '/');
this.router.navigate(['/system/organization']) this.router.navigate(['/system/organization'])
this.message.create('success', `登录成功`); this.message.create('success', `登录成功`);
},
(err) => { //调用服务中的function刷新token
this.isLoading = false; this.token.startUp()
this.message.create('error', err.error.error.details);
} }
) )
} }

12
src/app/service/cache-token.service.ts

@ -1,13 +1,12 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http' import { HttpClient } from '@angular/common/http'
import { CookieService } from 'ngx-cookie-service';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
export class CacheTokenService { export class CacheTokenService {
constructor(private http: HttpClient, private cookieService: CookieService) { } constructor(private http: HttpClient) { }
public timer: number | undefined; public timer: number | undefined;
@ -15,15 +14,14 @@ export class CacheTokenService {
startUp = (): void => { startUp = (): void => {
window.clearInterval(this.timer) window.clearInterval(this.timer)
this.timer = window.setInterval(() => { this.timer = window.setInterval(() => {
var token = this.cookieService.get("token"); var token = sessionStorage.getItem("token");
var refreshToken = this.cookieService.get("refreshToken"); var refreshToken = sessionStorage.getItem("refreshToken");
this.http.post('/api/CompanyAccount/RefreshToken', { this.http.post('/api/Accounts/RefreshToken', {
token: token, token: token,
refreshToken: refreshToken refreshToken: refreshToken
}).subscribe((data: any) => { }).subscribe((data: any) => {
sessionStorage.setItem("token", data.token); sessionStorage.setItem("token", data.token);
this.cookieService.set("token", data.token, undefined, '/'); sessionStorage.setItem("refreshToken", data.refreshToken);
this.cookieService.set("refreshToken", data.refreshToken, undefined, '/');
}) })
}, 18 * 60 * 1000) }, 18 * 60 * 1000)
} }

21
src/app/system-management/host-config/host-config.component.ts

@ -5,8 +5,9 @@ import { NzFormTooltipIcon } from 'ng-zorro-antd/form';
import { NzModalService } from 'ng-zorro-antd/modal'; import { NzModalService } from 'ng-zorro-antd/modal';
import { AddcameraComponent } from './addcamera/addcamera.component'; import { AddcameraComponent } from './addcamera/addcamera.component';
import { NzMessageService } from 'ng-zorro-antd/message'; import { NzMessageService } from 'ng-zorro-antd/message';
import { HttpClient } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { EditcameraComponent } from './editcamera/editcamera.component'; import { EditcameraComponent } from './editcamera/editcamera.component';
import { catchError, tap } from 'rxjs/operators';
interface Camera { interface Camera {
name: string; name: string;
user: string; user: string;
@ -132,7 +133,21 @@ export class HostConfigComponent implements OnInit {
} }
connect() { connect() {
this.router.navigate(['/system/host/camera/imageList']) let ids = []
} this.listOfData.forEach((item: any) => {
ids.push(item.id)
})
this.http.get('/api/Cameras/Statuses', {
params: { ids: ids }
}).subscribe({
next: (data) => {
console.log('连接状态', data)
},
error: (err) => {
console.log('连接失败', err)
},
// complete: () => console.log('complete!'), // not called
})
}
} }

4
src/app/system-management/navigation/navigation.component.ts

@ -1,5 +1,6 @@
import { Component, OnInit } from '@angular/core'; import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router'; import { Router } from '@angular/router';
import { CacheTokenService } from 'src/app/service/cache-token.service';
@Component({ @Component({
selector: 'app-navigation', selector: 'app-navigation',
@ -8,11 +9,12 @@ import { Router } from '@angular/router';
}) })
export class NavigationComponent implements OnInit { export class NavigationComponent implements OnInit {
constructor(private router: Router) { } constructor(private router: Router, public token: CacheTokenService) { }
ngOnInit(): void { ngOnInit(): void {
} }
signOut() { signOut() {
this.token.delete()
this.router.navigate(['/login']) this.router.navigate(['/login'])
} }
} }

Loading…
Cancel
Save