| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- // services/user.service.ts
- import { Injectable } from '@angular/core';
- @Injectable({
- providedIn: 'root'
- })
- export class UserService {
- private readonly STORAGE_KEY = 'registered_users';
- private readonly PROFILE_KEY = 'user_profiles';
- constructor() {}
- // 注册新用户
- async register(username: string, password: string): Promise<boolean> {
- const users = await this.getUsers();
-
- // 检查用户名是否已存在
- if (users.some(u => u.username === username)) {
- return false;
- }
-
- users.push({ username, password });
- localStorage.setItem(this.STORAGE_KEY, JSON.stringify(users));
- return true;
- }
- // 用户登录
- async login(username: string, password: string): Promise<boolean> {
- const users = await this.getUsers();
- const isLoggedIn = users.some(u => u.username === username && u.password === password);
-
- if (isLoggedIn) {
- localStorage.setItem('isLoggedIn', 'true');
- localStorage.setItem('currentUser', username); // 保存当前用户名
- }
- return isLoggedIn;
- }
- // 获取所有用户
- private async getUsers(): Promise<any[]> {
- const usersStr = localStorage.getItem(this.STORAGE_KEY);
- return usersStr ? JSON.parse(usersStr) : [];
- }
- // 保存当前用户
- setCurrentUser(username: string): void {
- localStorage.setItem('currentUser', username);
- localStorage.setItem('isLoggedIn', 'true');
- }
- // 获取当前用户
- getCurrentUser(): string | null {
- return localStorage.getItem('currentUser');
- }
- // 清除当前用户
- clearCurrentUser(): void {
- localStorage.removeItem('currentUser');
- localStorage.removeItem('isLoggedIn');
- }
- // 保存用户资料
- async saveProfile(username: string, profileData: any): Promise<boolean> {
- const profiles = await this.getProfiles();
- const existingIndex = profiles.findIndex(p => p.username === username);
-
- if (existingIndex >= 0) {
- profiles[existingIndex] = { username, ...profileData };
- } else {
- profiles.push({ username, ...profileData });
- }
-
- localStorage.setItem(this.PROFILE_KEY, JSON.stringify(profiles));
- return true;
- }
- // 获取用户资料
- async getProfile(username: string): Promise<any> {
- const profiles = await this.getProfiles();
- return profiles.find(p => p.username === username) || {};
- }
- // 获取所有用户资料
- private async getProfiles(): Promise<any[]> {
- const profilesStr = localStorage.getItem(this.PROFILE_KEY);
- return profilesStr ? JSON.parse(profilesStr) : [];
- }
- }
|