Browse Source

[新增]路由缓存

非煤矿业企业安全风险监测预警系统
邵佳豪 2 years ago
parent
commit
a2c7d80002
  1. 96
      src/app/CustomReuseStrategy.ts
  2. 25
      src/app/app.module.ts
  3. 252
      src/app/system-management/analysis-of-the-host/analysis-of-the-host.component.ts
  4. 2
      src/app/system-management/organization/organization.component.ts

96
src/app/CustomReuseStrategy.ts

@ -1,58 +1,64 @@
import { RouteReuseStrategy, ActivatedRouteSnapshot, DetachedRouteHandle } from '@angular/router'; import {
RouteReuseStrategy,
ActivatedRouteSnapshot,
DetachedRouteHandle,
} from '@angular/router';
export class CustomReuseStrategy implements RouteReuseStrategy { export class CustomReuseStrategy implements RouteReuseStrategy {
public static handlers: { [key: string]: DetachedRouteHandle } = {};
public static handlers: { [key: string]: DetachedRouteHandle } = {}; /** 删除缓存路由快照的方法 */
public static deleteRouteSnapshot(path: string): void {
/** 删除缓存路由快照的方法 */ const name = path.replace(/\//g, '_');
public static deleteRouteSnapshot(path: string): void { if (CustomReuseStrategy.handlers[name]) {
const name = path.replace(/\//g, '_'); delete CustomReuseStrategy.handlers[name];
if (CustomReuseStrategy.handlers[name]) {
delete CustomReuseStrategy.handlers[name];
}
} }
}
/** 表示对所有路由允许复用 如果你有路由不想利用可以在这加一些业务逻辑判断 */ /** 进入路由触发,判断是否同一路由 */
shouldDetach(route: ActivatedRouteSnapshot): boolean { shouldReuseRoute(
console.log('shouldDetach======>', route); future: ActivatedRouteSnapshot,
return true; curr: ActivatedRouteSnapshot
} ): boolean {
// console.debug('shouldReuseRoute======>', future, curr);
return (
future.routeConfig === curr.routeConfig &&
JSON.stringify(future.params) === JSON.stringify(curr.params)
);
}
/** 当路由离开时会触发。按path作为key存储路由快照&组件当前实例对象 */ /** 表示对所有路由允许复用 如果你有路由不想利用可以在这加一些业务逻辑判断 */
store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void { shouldDetach(route: ActivatedRouteSnapshot): boolean {
console.log('store======>', route, handle); console.log('shouldDetach======>', route);
if(route.routeConfig.path == 'host'){ return true;
CustomReuseStrategy.handlers[this.getRouteUrl(route)] = handle; }
}
}
/** 若 path 在缓存中有的都认为允许还原路由 */ /** 当路由离开时会触发。按path作为key存储路由快照&组件当前实例对象 */
shouldAttach(route: ActivatedRouteSnapshot): boolean { store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
// console.debug('shouldAttach======>', route); console.log('store======>', route, handle);
return !!CustomReuseStrategy.handlers[this.getRouteUrl(route)]; if (route.routeConfig.path == 'host') {
CustomReuseStrategy.handlers[this.getRouteUrl(route)] = handle;
} }
}
/** 从缓存中获取快照,若无则返回nul */ /** 若 path 在缓存中有的都认为允许还原路由 */
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle { shouldAttach(route: ActivatedRouteSnapshot): boolean {
// console.debug('retrieve======>', route); // console.debug('shouldAttach======>', route);
if (!CustomReuseStrategy.handlers[this.getRouteUrl(route)]) { return !!CustomReuseStrategy.handlers[this.getRouteUrl(route)];
return null; }
}
return CustomReuseStrategy.handlers[this.getRouteUrl(route)];
}
/** 进入路由触发,判断是否同一路由 */
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
// console.debug('shouldReuseRoute======>', future, curr);
return future.routeConfig === curr.routeConfig &&
JSON.stringify(future.params) === JSON.stringify(curr.params);
}
/** 使用route的path作为快照的key */ /** 从缓存中获取快照,若无则返回nul */
getRouteUrl(route: ActivatedRouteSnapshot) { retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
const path = route['_routerState'].url.replace(/\//g, '_'); // console.debug('retrieve======>', route);
return path; if (!CustomReuseStrategy.handlers[this.getRouteUrl(route)]) {
return null;
} }
return CustomReuseStrategy.handlers[this.getRouteUrl(route)];
}
/** 使用route的path作为快照的key */
getRouteUrl(route: ActivatedRouteSnapshot) {
const path = route['_routerState'].url.replace(/\//g, '_');
return path;
}
} }

25
src/app/app.module.ts

@ -6,8 +6,8 @@ import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { PagesModule } from './pages/pages.module'; import { PagesModule } from './pages/pages.module';
import { FormsModule } from '@angular/forms'; 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 { 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';
@ -15,9 +15,7 @@ import { RouteReuseStrategy } from '@angular/router';
import { CustomReuseStrategy } from './CustomReuseStrategy'; import { CustomReuseStrategy } from './CustomReuseStrategy';
import { ConfigFormDataService } from './service/configFormData.service'; import { ConfigFormDataService } from './service/configFormData.service';
@NgModule({ @NgModule({
declarations: [ declarations: [AppComponent],
AppComponent
],
imports: [ imports: [
BrowserModule, BrowserModule,
AppRoutingModule, AppRoutingModule,
@ -26,9 +24,18 @@ import { ConfigFormDataService } from './service/configFormData.service';
FormsModule, FormsModule,
HttpClientModule, HttpClientModule,
NzNotificationModule, NzNotificationModule,
NzMessageModule NzMessageModule,
],
providers: [
httpInterceptorProviders,
CacheTokenService,
TreeService,
ConfigFormDataService,
{
provide: RouteReuseStrategy,
useClass: CustomReuseStrategy,
},
], ],
providers: [httpInterceptorProviders, CacheTokenService, TreeService, ConfigFormDataService], bootstrap: [AppComponent],
bootstrap: [AppComponent]
}) })
export class AppModule { } export class AppModule {}

252
src/app/system-management/analysis-of-the-host/analysis-of-the-host.component.ts

@ -1,70 +1,100 @@
import { HttpClient } from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
import { Component, OnInit, AfterViewInit, ViewChild, ViewContainerRef } from '@angular/core'; import {
Component,
OnInit,
AfterViewInit,
ViewChild,
ViewContainerRef,
} from '@angular/core';
import { TreeService } from 'src/app/service/tree.service'; import { TreeService } from 'src/app/service/tree.service';
import { NzFormatEmitEvent, NzTreeComponent, NzTreeNodeOptions } from 'ng-zorro-antd/tree'; import {
NzFormatEmitEvent,
NzTreeComponent,
NzTreeNodeOptions,
} from 'ng-zorro-antd/tree';
import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzModalService } from 'ng-zorro-antd/modal'; import { NzModalService } from 'ng-zorro-antd/modal';
import { NzMessageService } from 'ng-zorro-antd/message'; import { NzMessageService } from 'ng-zorro-antd/message';
import { AddhostComponent } from './addhost/addhost.component'; import { AddhostComponent } from './addhost/addhost.component';
import { EdithostComponent } from './edithost/edithost.component'; import { EdithostComponent } from './edithost/edithost.component';
import { Router } from '@angular/router'; import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs';
@Component({ @Component({
selector: 'app-analysis-of-the-host', selector: 'app-analysis-of-the-host',
templateUrl: './analysis-of-the-host.component.html', templateUrl: './analysis-of-the-host.component.html',
styleUrls: ['./analysis-of-the-host.component.scss'] styleUrls: ['./analysis-of-the-host.component.scss'],
}) })
export class AnalysisOfTheHostComponent implements OnInit { export class AnalysisOfTheHostComponent implements OnInit {
constructor(
private router: Router,
private fb: FormBuilder,
private http: HttpClient,
private toTree: TreeService,
private modal: NzModalService,
private message: NzMessageService,
private viewContainerRef: ViewContainerRef
) {
router.events
.pipe(filter((e) => e instanceof NavigationEnd))
.subscribe((e) => {
if(this.selectedOilStation && this.selectedOilStation.id){
this.getHost();
}
constructor(private router: Router, private fb: FormBuilder, private http: HttpClient, private toTree: TreeService, private modal: NzModalService, private message: NzMessageService, private viewContainerRef: ViewContainerRef) { } });
}
ngOnInit(): void { ngOnInit(): void {
this.getAllOrganization() this.getAllOrganization();
} }
//获取所有组织机构 //获取所有组织机构
searchValue = ''; searchValue = '';
nzExpandAll = false; nzExpandAll = false;
totalCount: string totalCount: string;
getAllOrganization() { getAllOrganization() {
let params = { let params = {
ContainsChildren: true, ContainsChildren: true,
PageSize: 9999 PageSize: 9999,
} };
this.http.get('/api/Organizations', { this.http
params: params .get('/api/Organizations', {
}).subscribe((data: any) => { params: params,
this.totalCount = data.totalCount })
console.log(data.items) .subscribe((data: any) => {
data.items.forEach(element => { this.totalCount = data.totalCount;
element.key = element.id console.log(data.items);
element.title = element.name data.items.forEach((element) => {
element.selectable = false element.key = element.id;
if (element.isGasStation) { element.title = element.name;
element.isLeaf = true element.selectable = false;
} if (element.isGasStation) {
element.isLeaf = true;
}
});
this.nodes = [...this.toTree.toTree(data.items)];
this.defaultExpandedKeys = [this.nodes[0].id];
this.defaultExpandedKeys = [...this.defaultExpandedKeys];
}); });
this.nodes = [...this.toTree.toTree(data.items)]
this.defaultExpandedKeys = [this.nodes[0].id]
this.defaultExpandedKeys = [...this.defaultExpandedKeys]
})
} }
@ViewChild('nzTreeComponent', { static: false })
@ViewChild('nzTreeComponent', { static: false }) nzTreeComponent!: NzTreeComponent; nzTreeComponent!: NzTreeComponent;
defaultExpandedKeys = []; defaultExpandedKeys = [];
nodes: any[] = [] nodes: any[] = [];
nzSelectedKeys: any[] = [] nzSelectedKeys: any[] = [];
selectedOilStation: any selectedOilStation: any;
nzClick(event: NzFormatEmitEvent): void { nzClick(event: NzFormatEmitEvent): void {
if (event.node.origin['isGasStation']) {//如果点击的是加油站才生效 if (event.node.origin['isGasStation']) {
this.nzSelectedKeys[0] = event.node.origin.id //如果点击的是加油站才生效
this.nzSelectedKeys = [...this.nzSelectedKeys] this.nzSelectedKeys[0] = event.node.origin.id;
this.selectedOilStation = event.node.origin this.nzSelectedKeys = [...this.nzSelectedKeys];
console.log(this.selectedOilStation) this.selectedOilStation = event.node.origin;
this.getHost() console.log(this.selectedOilStation);
this.getHost();
} else { } else {
this.message.info('只有加油站才可以增加主机'); this.message.info('只有加油站才可以增加主机');
} }
@ -72,30 +102,29 @@ export class AnalysisOfTheHostComponent implements OnInit {
//获得加油站的主机 //获得加油站的主机
listOfData: any[] = []; listOfData: any[] = [];
isLoading = false isLoading = false;
getHost() { getHost() {
this.isLoading = true this.isLoading = true;
this.http.get('/api/EdgeDevices', { this.http
params: { .get('/api/EdgeDevices', {
ContainsChildren: true, params: {
OrganizationId: this.selectedOilStation.id, ContainsChildren: true,
PageSize: 999 OrganizationId: this.selectedOilStation.id,
} PageSize: 999,
}).subscribe((data: any) => { },
console.log('主机列表', data.items) })
this.isLoading = false .subscribe((data: any) => {
this.listOfData = data.items console.log('主机列表', data.items);
}) this.isLoading = false;
this.listOfData = data.items;
});
} }
ngAfterViewInit(): void {}
ngAfterViewInit(): void {
}
//新增边缘盒子 //新增边缘盒子
addHost() { addHost() {
console.log(this.selectedOilStation) console.log(this.selectedOilStation);
const modal = this.modal.create({ const modal = this.modal.create({
nzTitle: '新增边缘盒子', nzTitle: '新增边缘盒子',
nzContent: AddhostComponent, nzContent: AddhostComponent,
@ -104,105 +133,110 @@ export class AnalysisOfTheHostComponent implements OnInit {
nzComponentParams: {}, nzComponentParams: {},
nzOnOk: async () => { nzOnOk: async () => {
if (instance.validateForm.valid) { if (instance.validateForm.valid) {
await new Promise(resolve => { await new Promise((resolve) => {
console.log('表单信息', instance.validateForm) console.log('表单信息', instance.validateForm);
let body = { let body = {
hostIPAddress: instance.validateForm.value.ip, hostIPAddress: instance.validateForm.value.ip,
OrganizationId: this.selectedOilStation.id OrganizationId: this.selectedOilStation.id,
} };
this.http.post('/api/EdgeDevices', body).subscribe(data => { this.http.post('/api/EdgeDevices', body).subscribe((data) => {
resolve(data) resolve(data);
this.message.create('success', '创建成功!'); this.message.create('success', '创建成功!');
this.getHost() this.getHost();
return true return true;
}) });
}) });
} else { } else {
this.message.create('warning', '请填写完整!'); this.message.create('warning', '请填写完整!');
return false return false;
} }
} },
}); });
const instance = modal.getContentComponent(); const instance = modal.getContentComponent();
} }
edit(data) { edit(data) {
console.log(data) console.log(data);
const modal = this.modal.create({ const modal = this.modal.create({
nzTitle: '编辑边缘盒子', nzTitle: '编辑边缘盒子',
nzContent: EdithostComponent, nzContent: EdithostComponent,
nzViewContainerRef: this.viewContainerRef, nzViewContainerRef: this.viewContainerRef,
nzWidth: 288, nzWidth: 288,
nzComponentParams: { nzComponentParams: {
ip: data.hostIPAddress ip: data.hostIPAddress,
}, },
nzOnOk: async () => { nzOnOk: async () => {
if (instance.validateForm.valid) { if (instance.validateForm.valid) {
await new Promise(resolve => { await new Promise((resolve) => {
console.log('表单信息', instance.validateForm) console.log('表单信息', instance.validateForm);
data.hostIPAddress = instance.validateForm.value.ip, (data.hostIPAddress = instance.validateForm.value.ip),
this.http.put(`/api/EdgeDevices/${data.id}`, data).subscribe(data => { this.http
resolve(data) .put(`/api/EdgeDevices/${data.id}`, data)
this.message.create('success', '修改成功!'); .subscribe((data) => {
this.getHost() resolve(data);
return true this.message.create('success', '修改成功!');
}) this.getHost();
}) return true;
});
});
} else { } else {
this.message.create('warning', '请填写完整!'); this.message.create('warning', '请填写完整!');
return false return false;
} }
} },
}); });
const instance = modal.getContentComponent(); const instance = modal.getContentComponent();
} }
delete(item) { delete(item) {
console.log(item) console.log(item);
this.modal.confirm({ this.modal.confirm({
nzTitle: `确定要删除${item.name}这个主机吗?`, nzTitle: `确定要删除${item.name}这个主机吗?`,
nzOkText: '确定', nzOkText: '确定',
nzOkType: 'primary', nzOkType: 'primary',
nzOnOk: () => { nzOnOk: () => {
this.http.delete(`/api/EdgeDevices/${item.id}`).subscribe(data => { this.http.delete(`/api/EdgeDevices/${item.id}`).subscribe((data) => {
this.message.create('success', '删除成功!'); this.message.create('success', '删除成功!');
this.getHost() this.getHost();
}) });
}, },
nzCancelText: '取消' nzCancelText: '取消',
}); });
} }
config(data) { config(data) {
this.router.navigate([`/system/host/camera`], { queryParams: { 'hostId': data.id, 'orId': this.selectedOilStation.id } }) this.router.navigate([`/system/host/camera`], {
queryParams: { hostId: data.id, orId: this.selectedOilStation.id },
});
} }
download(data) { download(data) {
console.log(data) console.log(data);
let params = { let params = {
edgeDeviceId: data.id edgeDeviceId: data.id,
} };
const httpOptions = { const httpOptions = {
responseType: 'blob' as 'json', responseType: 'blob' as 'json',
params: params params: params,
}; };
this.http.get(`/api/EdgeDevices/IdentityDigest/File`, httpOptions).subscribe({ this.http
next: (data: any) => { .get(`/api/EdgeDevices/IdentityDigest/File`, httpOptions)
console.log('文件', data) .subscribe({
// 文件名中有中文 则对文件名进行转码 next: (data: any) => {
const link = document.createElement('a'); console.log('文件', data);
const blob = new Blob([data], { type: 'application/octet-stream' }); // 文件名中有中文 则对文件名进行转码
link.setAttribute('href', window.URL.createObjectURL(blob)); const link = document.createElement('a');
link.setAttribute('download', `.deviceid`); const blob = new Blob([data], { type: 'application/octet-stream' });
link.style.visibility = 'hidden'; link.setAttribute('href', window.URL.createObjectURL(blob));
document.body.appendChild(link); link.setAttribute('download', `.deviceid`);
link.click(); link.style.visibility = 'hidden';
document.body.removeChild(link); document.body.appendChild(link);
}, link.click();
error: (err) => { document.body.removeChild(link);
console.log(err) },
} error: (err) => {
}) console.log(err);
},
});
} }
} }

2
src/app/system-management/organization/organization.component.ts

@ -27,7 +27,7 @@ export class OrganizationComponent implements OnInit {
}); });
this.getAllOrganization() this.getAllOrganization()
this.deleteRouteSnapshot(); // this.deleteRouteSnapshot();
} }
deleteRouteSnapshot() { deleteRouteSnapshot() {
CustomReuseStrategy.deleteRouteSnapshot('/system/host'); CustomReuseStrategy.deleteRouteSnapshot('/system/host');

Loading…
Cancel
Save