步骤一:创建一个 AuthService(认证服务)来处理用户的登录和验证。使用 Angular CLI 命令创建:
ng generate service auth
步骤二:在相应的 auth.service.ts 文件中添加以下代码:
import { Injectable } from '@angular/core'; import { Router } from '@angular/router';
@Injectable({ providedIn: 'root' }) export class AuthService {
loggedInUserEmail: string;
constructor(private router: Router) {}
login(userEmail: string, password: string): boolean { // 登录逻辑 if (userEmail === 'test@test.com' && password === '123') { this.loggedInUserEmail = userEmail; this.router.navigate(['/dashboard']); return true; } return false; }
isLoggedIn(): boolean { return !!this.loggedInUserEmail; }
}
步骤三:创建一个 DashboardComponent(仪表板组件)并在其相应的 dashboard.component.ts 文件中添加以下代码:
import { Component, OnInit } from '@angular/core'; import { AuthService } from '../auth.service';
@Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.css'] }) export class DashboardComponent implements OnInit {
loggedInUserEmail: string;
constructor(private authService: AuthService) {}
ngOnInit() { if (this.authService.isLoggedIn()) { this.loggedInUserEmail = this.authService.loggedInUserEmail; } }
}
步骤四:在 DashboardComponent 的 HTML 模板中添加以下代码:
欢迎,{{loggedInUserEmail}}!
现在,当用户使用有效的电子邮件地址和密码登录时,Angular 应用程序将导航至仪表板,并显示欢迎消息和该用户的电子邮件地址。