app.component.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { Component, OnInit, effect } from '@angular/core';
  2. import { HttpErrorResponse } from '@angular/common/http';
  3. import { FormsModule } from '@angular/forms';
  4. import { RouterOutlet } from '@angular/router';
  5. import { finalize } from 'rxjs';
  6. import { ApiService } from './api.service';
  7. @Component({
  8. selector: 'app-root',
  9. standalone: true,
  10. imports: [FormsModule, RouterOutlet],
  11. templateUrl: './app.component.html',
  12. styleUrl: './app.component.scss',
  13. })
  14. export class AppComponent implements OnInit {
  15. accessKey = '';
  16. checking = false;
  17. error = '';
  18. constructor(readonly api: ApiService) {
  19. effect(() => {
  20. if (!this.api.authenticated()) this.accessKey = '';
  21. });
  22. }
  23. ngOnInit() {
  24. const savedKey = this.api.getSessionKey();
  25. if (!savedKey) return;
  26. this.accessKey = savedKey;
  27. this.unlock();
  28. }
  29. unlock() {
  30. const key = this.accessKey.trim();
  31. if (!key || this.checking) return;
  32. this.checking = true;
  33. this.error = '';
  34. this.api.authenticate(key).pipe(
  35. finalize(() => { this.checking = false; }),
  36. ).subscribe({
  37. error: (error: unknown) => {
  38. this.error = error instanceof HttpErrorResponse && error.status === 401
  39. ? '访问密钥不正确'
  40. : '暂时无法连接数据服务';
  41. },
  42. });
  43. }
  44. }