import { Component } from '@angular/core'; import {NgForOf} from "@angular/common"; import {NzTabComponent, NzTabSetComponent} from "ng-zorro-antd/tabs"; import {ActivationEnd, Router, RouterOutlet} from "@angular/router"; import {filter} from "rxjs"; import {MenuService} from "../../../servies/menu/menu.service"; import {BrowserStorageService} from "../../../utils/localStorage.service"; import {DATA} from "../../../data/login/localStorage.namespace"; import {menuData} from "../../../data/menu/menu.namespace"; @Component({ selector: 'app-tab', standalone: true, imports: [ NgForOf, NzTabComponent, NzTabSetComponent, RouterOutlet ], templateUrl: './tab.component.html', styleUrl: './tab.component.less' }) export class TabComponent { // 当前打开的Tab页 activatedMenuIndex = -1; // 存放已打开的Tab页信息 tabs: { path: string, title: string }[] = []; constructor(private router: Router) { // 监听路由事件,只订阅 ActivationEnd 事件 this.router.events.pipe(filter(e => e instanceof ActivationEnd)) .subscribe((e) => { // 这里不强转VS Code编译通不过,有没有大佬有解决方法 const thisEvt = e; console.log("路由监听" , thisEvt.snapshot.routeConfig?.path); if (thisEvt.snapshot.routeConfig?.loadChildren) { // 当前激活的路由 const activatedRoutePath = thisEvt.snapshot.routeConfig?.path; const routeData = thisEvt.snapshot.routeConfig?.data; let menuTitle = '新标签页'; if(routeData) { menuTitle = routeData['title']; } // 该路由是否已激活,激活过则直接打开 let isExist = false; this.tabs.every((t, i) => { if(activatedRoutePath === t.path) { this.activatedMenuIndex = i; isExist = true; return false; } return true; }); // 指定路由不在tabs中存在(未激活或激活后关闭) if(!isExist) { this.activeMenu(activatedRoutePath, menuTitle); } } }); } // 点击菜单激活指定路由并保存tab页签 activeMenu(menuPath: string | undefined, menuTitle: string): void { if(!menuPath) return; let menuIndex = -1; this.tabs.every((t, i) => { if(menuPath === t.path) { menuIndex = i; return false; } return true; }); if(menuIndex === -1) { this.tabs.push({path: menuPath, title: menuTitle}); menuIndex = this.tabs.length - 1; this.activatedMenuIndex = menuIndex; } } // 激活路由 activeRoute(path: string): void { this.router.navigateByUrl(path).finally(); } // 切换tab,激活对应路由 toggleTab(path: string): void { this.activeRoute(path); } // tab页签关闭,从缓存中删除对应信息 closeTab(path: string): void { if (1 === this.tabs.length) return; let selectedIndex = -1; this.tabs.every((t, i) => { if(t.path === path) { selectedIndex = i; return false; } return true; }); this.tabs.splice(selectedIndex, 1); if(selectedIndex === this.activatedMenuIndex) { let prevIndex = this.activatedMenuIndex - 1; this.activatedMenuIndex = prevIndex > 0 ? prevIndex : 0; this.activeRoute(this.tabs[this.activatedMenuIndex].path); }else if (this.activatedMenuIndex > selectedIndex) { this.activatedMenuIndex -= 1; } } }