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';

相關問題