网站搜索

javascript - 在 Angular 中调用接口


我有一个来自后端的接口是这样的:

export interface DailyGoal extends Base {
  date: Date;
  percentage: number;
}

现在我正在尝试在我的 component.ts 文件中引用它

import { DailyGoal } from '../../interfaces';
  dailyGoal: DailyGoal[] = [];

但我不明白如何将我拥有的变量应用到日期和百分比中。我创建了这个函数,它会给我用户可以选择的日期列表(我仍然需要弄清楚如何处理百分比)

   getDays(startDate: Date, endDate: Date) {
        const dates = [];
        const percentage = [];
        const currentDate = startDate;
        while (currentDate < endDate) {
          dates.push(new Date(currentDate));
          currentDate.setDate(currentDate.getDate() + 1);
        }

// for (let date of dates) {

    // if (date.getDay() <= 5) {
    //   percentage.push(100);
    // 
    // } else date.getDay() > 5;
    // percentage.push(0);


 if (startDate && endDate)  dates.push(endDate);
    return dates;
  }

我怎样才能将我的“date”变量传入接口?希望你能帮我,非常感谢

答案#1

每当你同时拥有日期和值的百分比时,你可以直接在 dailyGoal 数组上调用 push 方法:

this.dailyGoal.push({ date: theDate, percentage: thePercentage });

答案#2

TypeScript 的核心原则是它关注对象的 形状。也被称为 鸭子类型,而 接口 是一个有用的构造,用于为类型命名并应用类型检查(不要将类型与 TypeScript 构造 Type 混淆)。所以如果你的接口对象像

export interface DailyGoal extends Base {
  date: Date;
  percentage: number;
}

而基接口是这样的

export interface Base
{
number1: number;
string1: string;
}

那么,如果一个对象拥有 DailyGoal 和 Base 接口的所有 4 个属性,它就等同于 DailyGoal 接口。

this.dailyGoal.push({ date: theDate, percentage: thePercentage, number1: 0, string1: '' });

如果你在任何接口中跳过任何成员,你会得到……类型缺少 DailyGoal 类型中的以下属性……之类的错误。

如果你不想为 Base 接口的属性赋值,你可以通过在属性名后面添加 问号 (?) 来将它们设为可选,例如 number1?:number。在这种情况下,你就不必提供这些属性的值(它们默认会被初始化为 undefined)。