问题是在Angular中已成功登陆的用户没有存储在本地存储中。解决方法是在登录成功后将用户存储在本地存储中。以下是一个使用Angular的示例代码:
AuthService.ts
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http';
@Injectable({ providedIn: 'root' }) export class AuthService { URL = 'http://localhost:3000';
constructor(private http: HttpClient) { }
login(data) {
return this.http.post(${this.URL}/auth/login, data);
}
setLocalStore(user) { localStorage.setItem('user', JSON.stringify(user)); }
getLocalStore() { return JSON.parse(localStorage.getItem('user')); }
isLoggedIn() { const user = this.getLocalStore(); return user !== null; } }
登录组件
import { Component, OnInit } from '@angular/core'; import { AuthService } from '../auth.service';
@Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { email: string; password: string;
constructor(private authService: AuthService) { }
ngOnInit() { }
login() { const data = { email: this.email, password: this.password }; this.authService.login(data).subscribe(result => { this.authService.setLocalStore(result); console.log('Logged in successfully'); }, error => { console.log(error); }); } }
在AuthService中,我们定义了三个方法:setLocalStore(), getLocalStore()和isLoggedIn(),以便存储、获取和验证本地存储中的用户。在login()方法中,我们订阅了AuthService的login()方法,它返回成功登录的用户信息。在订阅之后,我们调用setLocalStore()方法并将结果存储在本地存储中。现在我们可以使用其他组件中的isLoggedIn()方法来验证是否有已登录的用户。