可以通过以下代码示例来实现Angular登录功能:
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from './auth.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent {
email: string;
password: string;
constructor(private authService: AuthService, private router: Router) {}
login() {
if (this.authService.login(this.email, this.password)) {
this.router.navigate(['/dashboard']);
} else {
alert('Invalid email or password');
}
}
}
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AuthService {
user = { email: 'example@mail.com', password: 'password' };
constructor() {}
login(email: string, password: string): boolean {
if (email === this.user.email && password === this.user.password) {
localStorage.setItem('user', JSON.stringify(this.user));
return true;
} else {
return false;
}
}
logout() {
localStorage.removeItem('user');
}
getUser() {
return JSON.parse(localStorage.getItem('user'));
}
}
以上代码实现了Angular登录功能。在用户提交表单后,将其输入与预定义的用户凭据进行比较。如果输入与凭据匹配,则将用户信息存储在浏览器