Home > Software design >  object is set but property returns undefined
object is set but property returns undefined

Time:07-22

I have created a class as below:

export class User{
    private _name:string

    User(){}

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

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

}

now in my code at login i am fetching data from server side and assigning it to a variable as below:

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)

Below is the response and the last line of printing name undefined is something i am not able to figure out

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

CodePudding user response:

There is no getter and setter, cause you haven't created an instance of User class. You've just assigned value returned from fetchCustomer to user property in the service.

So your code should be like:

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`
  • Related