【问题标题】:How to call moment function in angular app如何在角度应用程序中调用矩函数
【发布时间】:2018-09-26 09:03:13
【问题描述】:

我已经安装了moment.js 使用

 npm i  moment

将其包含在脚本中并尝试在 module.ts 中导入

当我试图在component.ts 中调用时刻时,它会给出一个错误

'找不到名字作为时刻'。

我做错了什么?

【问题讨论】:

  • 在 tsconfig 中指定 "moduleResolution": "node"。
  • 您还应该展示您当前是如何使用它的。显示相关代码。
  • 它已经在那里了
  • 我在您的问题中没有看到任何相关代码。

标签: angular typescript momentjs


【解决方案1】:

在你的组件中导入

import moment from 'moment';

你可以这样调用

moment(new Date)

【讨论】:

  • 以同样的方式完成
  • 使用'moment'的导入时刻;删除“* as”
【解决方案2】:

您是否尝试过使用以下方法:

npm install moment --save

npm install @types/moment --save

然后在 angular-cli.json 中添加 scripts 标签:

"scripts:" ["../node_modules/moment/min/moment/min"]

然后包含在组件中:

import * as moment from 'moment'

然后在组件方法中使用:

let now = moment();

console.log(now.format());

【讨论】:

  • 感谢 suraj yes just checked => Moment 提供了自己的类型定义,因此您现在不需要安装 @types/moment。
【解决方案3】:

首先,确保您已安装并保存moment.js

npm i moment --save

在您的component.ts 中,导入时刻如下:

import * as moment from 'moment';

//You should capable to use momentjs as followed.
console.log(moment(moment.now())).format('YYYY-MM-DD')

注意:如果您在导入时刻时遇到问题,请尝试在 tsconfig.json 文件的 compilerOptions 中添加 "allowSyntheticDefaultImports": true ,然后使用语法

import moment from 'moment';

Reference

【讨论】:

  • 这是最新的 v2.13.0+ 版本,其中包括打字稿定义。
  • 尝试使用tsc cli 并向我们展示您的tsconfig.json。你用的是什么版本的打字稿?
猜你喜欢
  • 2013-08-22
  • 2016-06-29
  • 2019-12-17
  • 1970-01-01
  • 2020-02-25
  • 1970-01-01
  • 2016-03-29
  • 1970-01-01
  • 2020-09-06
相关资源
最近更新 更多