【问题标题】:How to use Numeral.js library in angular2/ionic 2 typescript app?如何在 angular2/ionic 2 typescript 应用程序中使用 Numeral.js 库?
【发布时间】:2017-06-12 07:12:11
【问题描述】:

我已经成功地在我的 angularJs(1.x) 应用程序中使用 Numeral.js 库将我的数字格式化为不同的格式。这就是我使用 angular1 过滤器的方式:

filter.js

.filter('numeral', function () {
  return function (count) {
    var numericalFormat = numeral(count).format('0.0a');
    return numericalFormat;
  };
})

为此我关注了官方docs of Numeral.js 并使用 npm 安装。我还在 index.html 中引用了 nodemodules。

在浏览器中

<script src="node_modules/numeral/numeral.min.js"></script>

但它显示

ERROR ReferenceError: number is not defined 在 NumeralFilter.transform

最初我尝试使用 CDN 引用,它在浏览器中按预期工作。但是当我在真实设备上安装应用程序时,我收到一个错误“未定义数字”。

管道

import {Pipe,PipeTransform,Injectable} from "@angular/core"
@Pipe({
name:'numeralPipe'
})
@Injectable()
export class NumeralPipe implements PipeTransform{
    transform(count:any):any{ //eg: in count has value something like 52456.0
       var numericalFormat = numeral(count).format('0.0a');//error here
    return numericalFormat; // i have to format it like 52,5k
  }; 
} 

是否有任何类型脚本库用于格式化和操作数字,或者在 angular2 中有什么方法可以做到这一点?

【问题讨论】:

  • 尝试在import {Pipe,PipeTransform,Injectable} from "@angular/core"之后添加declare var numeral:any
  • 添加为答案。你可以接受和支持

标签: angular ionic2 angular-pipe numeral.js


【解决方案1】:

将包添加到节点模块文件夹

yarn add numeral

npm install numeral

然后导入到 Typescript 文件中

import * as numeral from 'numeral';

【讨论】:

    【解决方案2】:

    添加

    declare var numeral:any

    之后

    import {Pipe,PipeTransform,Injectable} from "@angular/core".
    

    【讨论】:

    • 嘿吉亚!我已经通过cdn在浏览器中取得了成功,但是当我构建它时,应用程序在设备上出现错误。所以我再次尝试通过 npm 安装它,我在浏览器中也遇到了同样的错误。我已经更新了我的问题。
    • 你确保 js 在 dist 文件夹中,发布你的文件结构。您正在使用角度 cli 吗?
    • 其实它是一个ionic-2应用。
    • 你使用 CDN 吗?还是你使用 lib 中的 JS?我认为 JS 未加载
    • 我不知道最好的方法,但是从节点模块,将 JS 复制到 www 文件夹并在 index.html 中相应地更改路径。 www 中的任何内容都将包含在构建中。
    猜你喜欢
    • 2016-05-12
    • 2017-01-12
    • 2017-12-19
    • 2016-08-28
    • 2016-11-04
    • 1970-01-01
    • 2017-09-04
    • 2016-12-12
    • 2017-07-03
    相关资源
    最近更新 更多