Priyashan Jayasankha
Priyashan Jayasankha

Reputation: 302

Assign values into a imported data model angular

I created a model like this:

export class User {
  firstName: string;
  lastName: string;
  email: string;
  faculty: string;
  academicYear: number;
  participatingEvents: Array<string>;
  myClubs: Array<{id: string, isPresident: boolean, isEventPlanner: boolean}>;
}

and use this model in a component to upload data in to firebase

export class TestComponent implements OnInit {

   message: string;
   user1: User;

   ngOnInit() {
      this.user1.firstName = 'PRIYASHAN';
      this.user1.lastName = 'JAYASANKHA';
      this.user1.email = '[email protected]';
      this.user1.faculty = 'UCSC';
      this.user1.academicYear = 1;
      this.user1.participatingEvents = ['ABC', 'DEF'];
      this.user1.myClubs = [
         {id: 'QQQ', isEventPlanner: true , isPresident: true},
         {id: 'WWW', isEventPlanner: false , isPresident: true}
      ];

      this.af.submitData(this.user1);
    }
}

but it is not working my console shows

enter image description here

Upvotes: 1

Views: 953

Answers (2)

Nicholas K
Nicholas K

Reputation: 15423

You get this error since user1 is undefined before you try to set values on it. Initialize the object before trying to access it.

user1: User;

ngOnInit() {
   this.user1 = new User();
   // ... rest of the code
}

Furthermore, you should create a constructor to initialize all these properties during objection creation. That way the code gets shorter and avoids typographical errors during development.

With these changes your code will look like:

export class User {
  constructor(
    public firstName: string,
    public lastName: string,
    public email: string,
    public faculty: string,
    public academicYear: number,
    public participatingEvents: Array<string>,
    public myClubs: Array<{
      id: string;
      isPresident: boolean;
      isEventPlanner: boolean;
    }>
  ) {}
}

Creation of object + initialization of its properties

  ngOnInit() {
    this.user1 = new User(
      "PRIYASHAN",
      "JAYASANKHA",
      "[email protected]",
      "UCSC",
      1,
      ["ABC", "DEF"],
      [
        { id: "QQQ", isEventPlanner: true, isPresident: true },
        { id: "WWW", isEventPlanner: false, isPresident: true }
      ]
    );
  }

Upvotes: 2

zmag
zmag

Reputation: 8251

user1 needs to be initialized even if you set a type.

user1: User = {} as User;

Upvotes: 1

Related Questions