[英]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.