可以通过使用Angular的路由守卫和服务来实现在成功登录后显示用户名的功能。下面是一个示例代码:
auth.service.ts的服务,用于处理用户认证和保存用户信息:import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private isAuthenticated: boolean = false;
private username: string = '';
constructor() { }
login(username: string, password: string): boolean {
// 实际的认证逻辑
// 如果认证成功,则设置isAuthenticated为true,并保存用户名
this.isAuthenticated = true;
this.username = username;
return true;
}
logout(): void {
// 登出逻辑
// 设置isAuthenticated为false,并清除用户名
this.isAuthenticated = false;
this.username = '';
}
isLoggedIn(): boolean {
return this.isAuthenticated;
}
getUsername(): string {
return this.username;
}
}
auth.guard.ts的路由守卫,用于检查用户是否已经登录:import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) { }
canActivate(): boolean {
if (this.authService.isLoggedIn()) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
AuthService来获取用户名并显示:import { Component, OnInit } from '@angular/core';
import { AuthService } from './auth.service';
@Component({
selector: 'app-username',
template: 'Welcome, {{ username }}
'
})
export class UsernameComponent implements OnInit {
username: string = '';
constructor(private authService: AuthService) { }
ngOnInit() {
this.username = this.authService.getUsername();
}
}
AuthGuard来保护需要登录才能访问的路由:import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from './auth.guard';
import { LoginComponent } from './login.component';
import { UsernameComponent } from './username.component';
const routes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'username', component: UsernameComponent, canActivate: [AuthGuard] },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
这样,在成功登录后,用户将被重定向到/username路由,并且UsernameComponent将显示用户的用户名。