Angular: Class with Array of Foreign Keys

267 Views Asked by At

I've built the class "meal" with two properties like in the tour of heroes tutorial from angular:

export class Meal {
  id: number;
  name: string;
}

Now I want to declare a class like "Mealplan". Each Mealplan should contain five Objects of Meal, like:

export class Mealplan {
  weekId: number;
  mealPlan: Meal[] = new Array(5)
}

Important is, that I want to add existing Meals to the Mealplan. I do not want to create new Objects of Meal. Is it more recommended to just refer to the Meal ID in Mealplan? For example:

  createDb() {
    const meal = [
      {
        id: 101,
        name: 'Tatar',
        price: 18.00,
        description: "Sojasauce / Chili / Crème fraîche / Tobiko"
      };

and

const mealPlan = [
 {
  id: 1,
  mealPlan: [101, 101, 101, 101, 101]
 }
]

Is this the best way I can handle this problem? Or would it be better to use a Map or List or something else?

1

There are 1 best solutions below

3
storm85049 On

You could associate a type to mealPlan like this:

export class Mealplan {
  weekId: number;
  mealPlan: [Meal, Meal, Meal, Meal, Meal];
}

Now, doing this would be invalid:

let plan = new MealPlan();
plan.mealPlan = [new Meal(),new Meal(),new Meal(),new Meal()];

whereas this is valid:

let plan = new MealPlan();
plan.mealPlan = [new Meal(),new Meal(),new Meal(),new Meal(), new Meal()];