繁体   English   中英

对象已设置但属性返回未定义

[英]object is set but property returns undefined

我创建了一个类,如下所示:

export class User{
    private _name:string

    User(){}

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

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

}

现在在我的登录代码中,我从服务器端获取数据并将其分配给如下变量:

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

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

  constructor() { }
}

登录.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)

下面是响应,最后一行打印名称 undefined 是我无法弄清楚的

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

没有 getter 和 setter,因为您还没有创建User类的实例。 您刚刚将fetchCustomer返回的值分配给服务中的用户属性。

所以你的代码应该是这样的:

export class User{
    private _name:string

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


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

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

const user = await this.dataSvc.fetchCustomer(resp.user.uid);
this.core.user = new User(user.name); // as mentioned in the comments your response contains `_name` property instead of `name`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM