如何在angular2模型上声明日期属性

Mak*_*rau 9 typescript ruby-on-rails-5 angular

我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)

但是当我运行"ng serve --port 9000"时,我收到以下错误:

Cannot find name 'date'.
Run Code Online (Sandbox Code Playgroud)

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

adh*_*ris 20

这是打字稿问题.date打字稿中没有类型.您可以使用它Date来指示本机javascript Date对象,但这只是字段的输入.Angular/TS不会为你强迫你的值进入Date对象.如果您的数据来自JSON源,则日期通常只是字符串(JSON不支持日期对象).


小智 5

请检查打字稿中支持的数据类型。

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

date数据类型在那里不可用。您可以根据需要使用字符串任何数据类型。


Dan*_*bar 5

您可以使用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;
}
Run Code Online (Sandbox Code Playgroud)