【问题标题】:how to declare a date attribute on angular2 model如何在 angular2 模型上声明日期属性
【发布时间】:2017-04-19 18:37:40
【问题描述】:

我正在使用 Rails 5 + Angular2 制作一个 Web 应用程序,并且我有一个名为“Books”的模型。我的问题是我有一个名为“books.ts”的文件,其中包含代码:

export class Book {
id: number;
author_one: string;
author_two: string;
author_three: string;
title: string;
subtitle: string;
publisher: string;
year: date;
city: string;
edition: number;
volume: number;
pages: number;
ISBN: string;
barcode: string;
}

但是当我运行“ng serve --port 9000”时,出现以下错误:

Cannot find name 'date'.

在我遇到与其他属性相同的问题之前,因为我使用的是“整数”,但我将其更改为“数字”并且它起作用了,所以我想知道这是否是 Angular 不理解某些类型的问题属性。但是在搜索互联网后,我还没有找到如何在 Angular 中声明“日期”类型的变量。 有没有办法声明日期类型的变量?或者我应该使用字符串并进行某种处理以将其用作日期?

【问题讨论】:

    标签: angular typescript ruby-on-rails-5


    【解决方案1】:

    这是一个打字稿问题。打字稿中没有 date 类型。您可以使用Date 来表示原生javascript Date 对象,但这只是字段的类型。 Angular/TS 不会为您强制将您的值转换为 Date 对象。如果您的数据来自 JSON 源,日期通常只是字符串(JSON 不支持日期对象)。

    【讨论】:

    • 我不知道这是一个与打字稿相关的问题。谢谢你。
    【解决方案2】:

    您可以使用 moment.js 来获得更简单的方法。

    import { Moment } from 'moment';
    
    export class Book {
        id: number;
        author_one: string;
        author_two: string;
        author_three: string;
        title: string;
        subtitle: string;
        publisher: string;
        year: Moment;
        city: string;
        edition: number;
        volume: number;
        pages: number;
        ISBN: string;
        barcode: string;
    }
    

    【讨论】:

      【解决方案3】:

      请检查 typescript 中支持的数据类型。

      https://www.typescriptlang.org/docs/handbook/basic-types.html

      date 数据类型在那里不可用。您可以根据需要使用 stringany 数据类型。

      【讨论】:

      • 我不知道这是一个与打字稿相关的问题。谢谢你。
      【解决方案4】:

      改用 JS 日期

      {
        id: string;
        name: string;
        description: string;
        status: number;
        active_from: Date;
        active_till: Date;
        data: any = {};
        created_at: Date;
        updated_at: Date;
      }
      

      并将其初始化为

      { 
        id: "abc123", 
        name: "Some name",
        description: "Some description",
        status: 1,
        active_from: new Date("Fri Dec 08 2019 07:44:57"),
        active_till: new Date("Fri Dec 08 2020 07:44:57"),
        data: {},
      
        created_at: new Date("Fri Dec 08 2019 07:44:57"),
        updated_at: new Date("Fri Dec 08 2019 07:44:57"),
      }
      

      【讨论】:

        【解决方案5】:

        javascript中没有日期类型,请使用Datejavascript类型。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-12-10
          • 2022-07-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-10-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多