Search code examples
angulartypescriptmodels

Object Declaration/Relationship in angular models


is it possible to do something like this I wanted to declare an object inside my model the first one i tried is

export class Employee{
    emp_id: number;
    emp_fname: string;
    emp_lname: string;
    emp_birth: string;
    emp_status: string;
    emp_photo: string;
    emp_department: string; 
    department: Array<object> = 
    [{
        dept_id: number;
        dept_name: string;
    }];

the second one was like this

import { Department } from "./department.model";

export class Employee{
  constructor(department: Department){};
    emp_id: number;
    emp_fname: string;
    emp_lname: string;
    emp_birth: string;
    emp_status: string;
    emp_photo: string;
    emp_department: string; 
    department: department;

}

both return errors in my terminal: first one returns expects , but when i make it so it says that I should use eg:number as type not as value.

Then the second one returns an error

Cannot find name 'department'.

my department model

export class Department {
    dept_id: number;
    dept_name: string;
}

Solution

  • export class Department {
        dept_id: number;
        dept_name: string;
        constructor(dept_id, dept_name){
            this.dept_id = dept_id;
            this.dept_name = dept_name;
        }
    }
    
    export class Employee{
        emp_id: number;
        emp_fname: string;
        emp_lname: string;
        emp_birth: string;
        emp_status: string;
        emp_photo: string;
        emp_department: string; 
        department: Department[] = [new Department(1, "dept_name1"), new Department(2, "dept_name2")];
    }