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

Angular中User类getter属性name返回undefined问题

Angular中User类getter获取name返回undefined问题排查

问题场景

定义了包含name getter/setter的User类,从服务器获取用户数据赋值给CoreService的user变量后,控制台能看到对象包含_name属性,但通过this.core.user.name获取时返回undefined。

涉及代码

User类

export class User{
    private _name:string

    User(){}

    get name():string{
        return this._name
    }

    set name(val:string){
        this._name = val
    }

}

CoreService

import { Injectable } from '@angular/core';
import { User } from './modal/user.modal';

@Injectable({
  providedIn: 'root'
})
export class CoreService {
  user:User

  constructor() { }
}

login.ts逻辑

this.core.user = await this.dataSvc.fetchCustomer(resp.user.uid)
console.log("user is:", Object.keys(this.core.user))
console.log("user is:", Object.values(this.core.user))

console.log("user is:", this.core.user)
console.log("user name is:", this.core.user.name)

控制台输出

user is: 
Array(5) [ "_email", "_joinDate", "_name", "_phone", "_uid" ]
main.js:469:17
user is: 
Array(5) [ "vik.ceo@gmail.com", 1658372252068, "Vivek Kumar", "6508670697", "AoaFKbEzrYcjZUE283rI4dpSYh92" ]
main.js:470:17
user is: 
Object { _email: "vik.ceo@gmail.com", _joinDate: 1658372252068, _name: "Vivek Kumar", _phone: "6508670697", _uid: "AoaFKbEzrYcjZUE283rI4dpSYh92" }
main.js:471:17
user name is: undefined

问题原因及解决方案

1. 构造函数写法错误

TypeScript中类的构造函数必须使用constructor关键字,原代码中的User(){}只是普通方法,不会在创建实例时执行;且直接赋值的服务器返回对象并非User类实例,不具备类定义的getter方法。

2. 普通对象未转换为User实例

服务器返回的是普通JavaScript对象,即使TypeScript声明类型为User,运行时仍为普通对象,没有User类的getter逻辑,无法通过.name访问_name属性。

修改后的User类

export class User{
    private _name:string;
    private _email:string;
    private _joinDate:number;
    private _phone:string;
    private _uid:string;

    // 修正构造函数,支持传入数据初始化
    constructor(data?: Partial<User>){
        if(data){
            // 对应服务器返回的字段名赋值
            this._name = data._name;
            this._email = data._email;
            this._joinDate = data._joinDate;
            this._phone = data._phone;
            this._uid = data._uid;
        }
    }

    get name():string{
        return this._name;
    }

    set name(val:string){
        this._name = val;
    }

    // 按需添加其他属性的getter
    get email():string{
        return this._email;
    }

    get joinDate():number{
        return this._joinDate;
    }
}

修改login.ts赋值逻辑

将服务器返回的普通对象转换为User实例:

const userData = await this.dataSvc.fetchCustomer(resp.user.uid);
// 创建User实例并传入数据
this.core.user = new User(userData);

console.log("user is:", Object.keys(this.core.user));
console.log("user is:", Object.values(this.core.user));
console.log("user is:", this.core.user);
console.log("user name is:", this.core.user.name);

或者使用Object.assign复制属性到实例:

this.core.user = new User();
Object.assign(this.core.user, await this.dataSvc.fetchCustomer(resp.user.uid));

修改后,this.core.user.name即可正确返回_name的值。

内容的提问来源于stack exchange,提问作者Vivek K

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 13:48:23