import { Component, OnInit, effect } from '@angular/core'; import { HttpErrorResponse } from '@angular/common/http'; import { FormsModule } from '@angular/forms'; import { RouterOutlet } from '@angular/router'; import { finalize } from 'rxjs'; import { ApiService } from './api.service'; @Component({ selector: 'app-root', standalone: true, imports: [FormsModule, RouterOutlet], templateUrl: './app.component.html', styleUrl: './app.component.scss', }) export class AppComponent implements OnInit { accessKey = ''; checking = false; error = ''; constructor(readonly api: ApiService) { effect(() => { if (!this.api.authenticated()) this.accessKey = ''; }); } ngOnInit() { const savedKey = this.api.getSessionKey(); if (!savedKey) return; this.accessKey = savedKey; this.unlock(); } unlock() { const key = this.accessKey.trim(); if (!key || this.checking) return; this.checking = true; this.error = ''; this.api.authenticate(key).pipe( finalize(() => { this.checking = false; }), ).subscribe({ error: (error: unknown) => { this.error = error instanceof HttpErrorResponse && error.status === 401 ? '访问密钥不正确' : '暂时无法连接数据服务'; }, }); } }