user.service.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // services/user.service.ts
  2. import { Injectable } from '@angular/core';
  3. @Injectable({
  4. providedIn: 'root'
  5. })
  6. export class UserService {
  7. private readonly STORAGE_KEY = 'registered_users';
  8. private readonly PROFILE_KEY = 'user_profiles';
  9. constructor() {}
  10. // 注册新用户
  11. async register(username: string, password: string): Promise<boolean> {
  12. const users = await this.getUsers();
  13. // 检查用户名是否已存在
  14. if (users.some(u => u.username === username)) {
  15. return false;
  16. }
  17. users.push({ username, password });
  18. localStorage.setItem(this.STORAGE_KEY, JSON.stringify(users));
  19. return true;
  20. }
  21. // 用户登录
  22. async login(username: string, password: string): Promise<boolean> {
  23. const users = await this.getUsers();
  24. const isLoggedIn = users.some(u => u.username === username && u.password === password);
  25. if (isLoggedIn) {
  26. localStorage.setItem('isLoggedIn', 'true');
  27. localStorage.setItem('currentUser', username); // 保存当前用户名
  28. }
  29. return isLoggedIn;
  30. }
  31. // 获取所有用户
  32. private async getUsers(): Promise<any[]> {
  33. const usersStr = localStorage.getItem(this.STORAGE_KEY);
  34. return usersStr ? JSON.parse(usersStr) : [];
  35. }
  36. // 保存当前用户
  37. setCurrentUser(username: string): void {
  38. localStorage.setItem('currentUser', username);
  39. localStorage.setItem('isLoggedIn', 'true');
  40. }
  41. // 获取当前用户
  42. getCurrentUser(): string | null {
  43. return localStorage.getItem('currentUser');
  44. }
  45. // 清除当前用户
  46. clearCurrentUser(): void {
  47. localStorage.removeItem('currentUser');
  48. localStorage.removeItem('isLoggedIn');
  49. }
  50. // 保存用户资料
  51. async saveProfile(username: string, profileData: any): Promise<boolean> {
  52. const profiles = await this.getProfiles();
  53. const existingIndex = profiles.findIndex(p => p.username === username);
  54. if (existingIndex >= 0) {
  55. profiles[existingIndex] = { username, ...profileData };
  56. } else {
  57. profiles.push({ username, ...profileData });
  58. }
  59. localStorage.setItem(this.PROFILE_KEY, JSON.stringify(profiles));
  60. return true;
  61. }
  62. // 获取用户资料
  63. async getProfile(username: string): Promise<any> {
  64. const profiles = await this.getProfiles();
  65. return profiles.find(p => p.username === username) || {};
  66. }
  67. // 获取所有用户资料
  68. private async getProfiles(): Promise<any[]> {
  69. const profilesStr = localStorage.getItem(this.PROFILE_KEY);
  70. return profilesStr ? JSON.parse(profilesStr) : [];
  71. }
  72. }