You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中如何实现组件间可访问的全局用户名变量?

项目结构截图

项目结构截图

现有代码说明

我通过登录界面获取用户名,相关代码如下:

login.component.html

<form [formGroup]="loginForm" #ngForm="ngForm" (ngSubmit)="submitForm()" class="login-form">
  <mat-card-content>
    <p class="content">Username:<span>*</span></p>
    <input type="text" formControlName="userName" id="userName" autocomplete="off">
    <div class="form-group"  *ngIf="userError">
      <p class="alert1 alert-danger">
          <strong>Required: </strong>Username

login.component.ts

.....
import { Component, OnInit, ViewChild } from '@angular/core';
import { NgForm, FormGroup, FormControl } from '@angular/forms';
import { Router } from '@angular/router';
import { Location } from '@angular/common';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  @ViewChild('ngForm') ngForm: NgForm;

  loginForm = new FormGroup({
    userName: new FormControl(),
    userPass: new FormControl()
  });

  userError: boolean = false;
  passError: boolean = false;

  constructor(private router: Router, private location: Location) { }

  ngOnInit() {
    if (sessionStorage.length != 0) {
      this.location.replaceState('/tool');
      this.router.navigate(['/tool']);
    }
  }

  submitForm() {
    if ((this.loginForm.value.userPass == null && 
         this.loginForm.value.userName == null)) {
      this.userError = true;
      this.passError = true;
      setTimeout(() => {
        this.userError = false;
        this.passError = false;
      }, 4000);

......

//新增代码
else {
      if (this.loginForm.value.userName != "" && this.loginForm.value.userPass != "") {
        sessionStorage.setItem(this.loginForm.value.userName, this.loginForm.value.userPass);
        localStorage.set("user", JSON.stringify(this.loginForm.value.userName)); // 此处插入的新增代码
        let userName = JSON.parse(localStorage.get("user")); // 此处也是新增代码
        this.location.replaceState('/tool');
        this.router.navigate(['/tool']);
      }
    }
  }

buyback.component.ts

....

export class BuybackComponent implements OnInit {

  constructor(private _buybackService: BuybackService, private router: Router, private location: Location) { }

  userName:String; //新增代码
  arbNumber:String;
  arbNumber2:String;
  bType:String;
  optionValue:String;
  choice:String;
  buybackAmt:String;
  buybackTypeChoice:String

.....
需求

我需要让buyback.component.ts能访问登录时获取的用户名,和arbNumber、choice等变量一同交互,请问怎么实现全局共享用户名?

解决方案

方式一:使用Angular全局服务(推荐)

这是Angular中共享状态的标准方式,适合复杂场景且能统一管理用户信息。

  1. 创建全局用户服务UserService
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root' // 全局注入,整个应用可用
})
export class UserService {
  private currentUser: string | null = null;

  // 设置当前用户,同时存入localStorage做持久化
  setUser(userName: string): void {
    this.currentUser = userName;
    localStorage.setItem('currentUser', JSON.stringify(userName));
  }

  // 获取当前用户,优先从内存取,内存没有则读localStorage
  getUser(): string | null {
    if (!this.currentUser) {
      const storedUser = localStorage.getItem('currentUser');
      this.currentUser = storedUser ? JSON.parse(storedUser) : null;
    }
    return this.currentUser;
  }
}
  1. 在登录组件中注入服务并设置用户
    先修正原代码中localStorage.set和localStorage.get的语法错误(正确方法是setItem和getItem),然后替换为服务调用:
// 导入UserService
import { UserService } from '../services/user.service';

// 构造函数注入服务
constructor(
  private router: Router, 
  private location: Location,
  private userService: UserService // 新增注入
) { }

// 修改submitForm中的else分支
else {
  if (this.loginForm.value.userName != "" && this.loginForm.value.userPass != "") {
    sessionStorage.setItem(this.loginForm.value.userName, this.loginForm.value.userPass);
    // 使用服务设置用户
    this.userService.setUser(this.loginForm.value.userName);
    this.location.replaceState('/tool');
    this.router.navigate(['/tool']);
  }
}
  1. 在Buyback组件中获取用户名
// 导入UserService
import { UserService } from '../services/user.service';

// 构造函数注入服务
constructor(
  private _buybackService: BuybackService, 
  private router: Router, 
  private location: Location,
  private userService: UserService // 新增注入
) { }

ngOnInit(): void {
  // 获取用户名赋值给组件变量
  this.userName = this.userService.getUser() || '';
  // 之后即可和arbNumber、choice等变量一起使用
}

方式二:直接读取localStorage(简单场景用)

如果不需要复杂状态管理,可直接在Buyback组件中读取存储的用户名:

ngOnInit(): void {
  // 先修正原代码的localStorage语法错误
  const storedUser = localStorage.getItem('user');
  this.userName = storedUser ? JSON.parse(storedUser) : '';
}

内容的提问来源于stack exchange,提问作者Johny Leo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 23:32:26