import {Component, OnInit} from '@angular/core'; // 路由 import {NavigationStart, Router} from '@angular/router'; // 国际化服务 import {TranslateService} from '@ngx-translate/core'; // 路由事件 import {Observable} from 'rxjs'; import {filter} from 'rxjs/operators'; // cookie操作 import {CookieService} from 'ngx-cookie-service'; // 环境变量 import {environment} from '../environments/environment'; import {LoginService} from './account/login/login.service'; import {Result} from './interface/Result'; import {MessageService} from './message/message.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit { // 登陆状态 isLogin = false; // 当前登陆账户 managerName = null; navStart: Observable; /** * * @param translate 国际化 * @param router 路由器 * @param cookieService cookie管理服务 * @param loginService 登陆服务 * @param messageService 信息反馈服务 */ constructor( public translate: TranslateService, private router: Router, private cookieService: CookieService, private loginService: LoginService, private messageService: MessageService, ) { this.navStart = router.events.pipe( filter(evt => evt instanceof NavigationStart) ) as Observable; } /** * 注销登录 */ logout() { this.loginService.logout().subscribe(r => { if (r.result === Result.OK) { this.cookieService.deleteAll(); this.messageService.info('注销成功'); this.router.navigateByUrl('/login'); } else { alert('注销失败'); } }); } async ngOnInit() { this.navStart.subscribe(evt => { this.isLogin = this.cookieService.check(environment.tokenKey); this.managerName = this.cookieService.get(environment.managerKey); if (evt.url !== '/forum' && this.isLogin) { this.router.navigateByUrl('/forum'); } else if (evt.url !== '/login' && !this.isLogin) { this.router.navigateByUrl('/login'); } else { console.debug('当前路由' + evt.url + '不需要重定向'); } }); // 语言初始化(若未设置语言, 则取浏览器语言) const currentLanguage = await localStorage.getItem('currentLanguage') || this.translate.getBrowserCultureLang(); // 当在assets/i18n中找不到对应的语言翻译时,使用'zh-CN'作为默认语言 this.translate.setDefaultLang('zh-CN'); this.translate.use(currentLanguage); // 记录当前设置的语言 localStorage.setItem('currentLanguage', currentLanguage); } }