|
|
|
import {Component} 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';
|
|
|
|
|
|
|
|
@Component({
|
|
|
|
selector: 'app-root',
|
|
|
|
templateUrl: './app.component.html',
|
|
|
|
styleUrls: ['./app.component.scss']
|
|
|
|
})
|
|
|
|
export class AppComponent {
|
|
|
|
|
|
|
|
// 登陆状态
|
|
|
|
isLogin = this.cookieService.check(environment.tokenKey);
|
|
|
|
|
|
|
|
navStart: Observable<NavigationStart>;
|
|
|
|
|
|
|
|
/**
|
|
|
|
*
|
|
|
|
* @param translate 国际化
|
|
|
|
* @param router 路由器
|
|
|
|
* @param cookieService cookie管理服务
|
|
|
|
*/
|
|
|
|
constructor(public translate: TranslateService, private router: Router, private cookieService: CookieService) {
|
|
|
|
this.navStart = router.events.pipe(
|
|
|
|
filter(evt => evt instanceof NavigationStart)
|
|
|
|
) as Observable<NavigationStart>;
|
|
|
|
}
|
|
|
|
|
|
|
|
public async ngOnInit() {
|
|
|
|
this.navStart.subscribe(evt => {
|
|
|
|
|
|
|
|
if (evt.url === '/' && this.isLogin) {
|
|
|
|
this.router.navigateByUrl('/forum');
|
|
|
|
} else if (evt.url === '/') {
|
|
|
|
this.router.navigateByUrl('/login');
|
|
|
|
} else {
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
// 语言初始化(若未设置语言, 则取浏览器语言)
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|