简体   繁体   English

安装了 npm package 但在浏览器中出现“不是函数”错误

[英]installed npm package but get “is not a function” error in browser

I'm using Ionic 4 and trying to use this lib: https://date-fns.org to get a date string like 2019-11-01 07:23:22 to be displayed in human readable way.我正在使用Ionic 4并尝试使用这个库: https://date-fns.org来获取像2019-11-01 07:23:22这样的日期字符串,以便以人类可读的方式显示。

So I've installed the lib with:所以我安装了lib:

npm install date-fns --save

Then in mypage.ts file然后在mypage.ts文件中

import { format, formatDistance, parseISO } from 'date-fns';

And then in mypage.html file然后在mypage.html文件中

<div class="date">{{ formatDistance(parseISO(h.created_at)) }}</div>

So I'm getting this error in browser console:所以我在浏览器控制台中收到此错误:

ERROR TypeError: _co.parseISO is not a function

It says the function doesn't exists, but it's in the docs: https://date-fns.org/v2.6.0/docs/parseISO它说 function 不存在,但它在文档中: https://date-fns.org/v2.6.0/docs/parseISO

Am I doing something wrong?难道我做错了什么?

In TS file:在 TS 文件中:

import { format, formatDistance, parseISO } from 'date-fns';

constructor(public formatDistance: formatDistance) {
}

This is HTML这是 HTML

<div class="date">{{ formatDistance(parseISO(h.created_at)) }}</div>

Only instance members of the components class can be called from the view.只能从视图调用组件 class 的实例成员。

https://stackoverflow.com/a/41857120/7562674 https://stackoverflow.com/a/41857120/7562674

In Ts File:-在 Ts 文件中:-

import { Component } from '@angular/core';
import { format, formatDistance, parseISO } from 'date-fns';

export class AppComponent implements OnInit {

formatDistance=formatDistance;
parseISO=parseISO;  
date=  "2018-10-01";
d=new Date(2015, 0, 1)
constructor(){
  console.log(formatDistance(parseISO("2018-10-01"), new Date(2015, 0, 
  1)))
  }

In template:-在模板中:-

  <p>{{formatDistance(parseISO(date),d)}}</p>

I checked this is working.我检查了这是有效的。

Declare as variable and assign it instead of injecting in constructor argument.声明为变量并分配它而不是注入构造函数参数。 Since it is a function not a class that why showing error not as type when used in constructor.由于它是 function 而不是 class,为什么在构造函数中使用时显示错误不是类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM