Angular中如何在home.component.html显示userName值?getUserName方法失效
解决Angular中Home组件无法显示登录用户名的问题
看起来你遇到的核心问题是AuthService没有持久存储登录用户的信息,同时HomeComponent也没有正确获取到当前登录的用户数据,导致模板里的{{ userName }}无法渲染出值。下面是一步步的解决方案:
第一步:修改AuthService,添加用户信息存储
首先我们需要在AuthService中添加一个用于保存当前登录用户的可观察对象,这样组件可以订阅它来获取实时的用户信息:
// auth/auth.service.ts import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { User } from './user'; @Injectable() export class AuthService { private loggedIn = new BehaviorSubject<boolean>(false); // 新增:存储当前登录用户,初始值为null private currentUserSubject = new BehaviorSubject<User | null>(null); get isLoggedIn() { return this.loggedIn.asObservable(); } // 新增:对外暴露用户信息的Observable get currentUser$() { return this.currentUserSubject.asObservable(); } constructor( private router: Router ) {} login(user: User) { if (user.userName !== '' && user.password !== '' ) { this.loggedIn.next(true); // 新增:登录成功后保存用户信息 this.currentUserSubject.next(user); this.router.navigate(['/']); } } // 这个方法可以移除了,因为我们通过currentUser$直接获取用户信息 // getUserName(user: User) { // return user.userName; // } logout() { this.loggedIn.next(false); // 新增:登出时清空用户信息 this.currentUserSubject.next(null); this.router.navigate(['/login']); } }
第二步:修改HomeComponent获取用户信息
有两种方式可以在HomeComponent中获取并显示用户名,推荐使用Async管道(无需手动订阅/取消订阅,避免内存泄漏):
方式一:使用Async管道(推荐)
修改home.component.ts:
// home/home.component.ts import {AuthService} from './../auth/auth.service'; import {Component} from '@angular/core'; import {User} from '../auth/user'; import { Observable } from 'rxjs'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styles: [] }) export class HomeComponent { // 定义用户信息的Observable currentUser$: Observable<User | null>; constructor(private authService: AuthService) { // 从服务中获取用户Observable this.currentUser$ = this.authService.currentUser$; } }
然后修改home.component.html模板:
<p> You are logged in! {{ (currentUser$ | async)?.userName }} </p>
这里的
?.是可选链操作符,避免用户未登录时出现空指针错误。
方式二:手动订阅(需要处理取消订阅)
如果你更习惯手动订阅,可以这样修改:
// home/home.component.ts import {AuthService} from './../auth/auth.service'; import {Component, OnInit, OnDestroy} from '@angular/core'; import {User} from '../auth/user'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styles: [] }) export class HomeComponent implements OnInit, OnDestroy { userName: string = ''; private userSubscription!: Subscription; constructor(private authService: AuthService) { } ngOnInit() { // 订阅用户信息 this.userSubscription = this.authService.currentUser$.subscribe(user => { if (user) { this.userName = user.userName; } }); } // 组件销毁时取消订阅,防止内存泄漏 ngOnDestroy() { this.userSubscription.unsubscribe(); } }
模板保持你原来的代码即可:
<p> You are logged in! {{ userName }} </p>
第三步:验证登录流程
现在当你在LoginComponent提交表单时,authService.login(this.form.value)会把表单里的用户信息传递到AuthService并存储起来,HomeComponent通过订阅currentUser$就能实时获取到登录的用户名并显示在模板中了。
内容的提问来源于stack exchange,提问作者user2129896
相关产品推荐
相关产品推荐

