2017-06-12 79 views
0

我已经成功地在我的angularJs(1.x)应用程序中使用Numeral.js库来格式化我的数字。这是我如何使用angular1过滤器:如何在angular2/ionic 2 typescript应用程序中使用Numeral.js库?

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: numeral is not defined at 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做到这一点?

+1

尝试加入'声明VAR数字:后'进口来自 “@角/芯”' –

+0

添加答案{管,PipeTransform,注射} any'。你可以接受&Upvote –

回答

1

添加

declare var numeral:any

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

嘿Gyaya!我通过cdn在浏览器中取得了成功,但是当我构建它的应用程序在设备上出现错误时。所以我试图通过npm再次安装它,我也得到了同样的错误。我已更新我的问题。 –

+0

你确保js在dist文件夹中,发布你的文件结构。你正在使用角度cli? –

+0

实际上它是一个离子-2应用程序。 –

3

附加包节点模块文件夹

yarn add numeral 

npm install numeral 

然后导入到打字稿文件

import * as numeral from 'numeral';

相关问题