【问题标题】:Angular: Class with Array of Foreign KeysAngular:具有外键数组的类
【发布时间】:2020-01-17 18:59:53
【问题描述】:

我已经建立了具有两个属性的“膳食”类,例如来自 angular 的英雄之旅教程:

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

现在我想声明一个像“Mealplan”这样的类。每个膳食计划应包含五个膳食对象,例如:

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

重要的是,我想将现有膳食添加到膳食计划中。我不想创建新的用餐对象。是否更建议仅参考 Mealplan 中的膳食 ID?例如:

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

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

这是我处理这个问题的最好方法吗?还是使用 Map 或 List 或其他东西会更好?

【问题讨论】:

    标签: angular typescript in-memory-database angular-tour-of-heroes


    【解决方案1】:

    你可以像这样将一个类型关联到mealPlan:

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

    现在,这样做无效

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

    而这是有效

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

    【讨论】:

    • 你好。感谢您的评论,但我认为我不应该在膳食计划中创建新对象。我已经编辑了我的开篇文章,您还有其他想法吗?
    • 我为你创建了一个小例子stackblitz.com/edit/json-pipe-example-4vbixg
    • 感谢您的努力!我理解你的观点,我认为这是一个很好的解决方案。但是,我需要弄清楚如何使用 in-memory-db 来做到这一点。 PS:我也是汉堡的! :D @storm85049
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多