当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > 在 Angular中 使用 Lodash 的方法

在 Angular中 使用 Lodash 的方法

2018年02月17日  | 移动技术网IT编程  | 我要评论

如何lodash 是 javascript 很有名的 package,尤其對於處理 array 很有一套,angular 該如何使用 lodash 呢 ? 這也可以視為在 angular 使用傳統 javascript package 的 sop。

version

node.js 8.9.4

angular cli 1.6.2

angular 5.2.2

安裝 lodash

~/myproject $ npm install lodash --save

使用 npm 安裝 lodash 。

安裝 lodash type 定義檔

~/myproject $ npm install @types/lodash --save-dev

傳統 javascript 並沒有型別,但 typescript 是個強型別語言,除了型別外還有泛型,這該怎麼與傳統 javascript 搭配呢 ?

typescript 的解決方案是另外使用 *.d.ts ,此為 type 定義檔。

一般來說,若是知名的 javascript library,都已經有人維護 type 定義檔,其 package 的規則是 @types/package 。

由於 type 定義檔只是 typescript 編譯使用,以此加上 --save-dev 。

tsconfig.json
{
 "compileonsave": false,
 "compileroptions": {
  "outdir": "./dist/out-tsc",
  "sourcemap": true,
  "declaration": false,
  "moduleresolution": "node",
  "emitdecoratormetadata": true,
  "experimentaldecorators": true,
  "target": "es5",
  "typeroots": [
   "node_modules/@types"
  ],
  "types" : ["lodash"],
  "lib": [
   "es2017",
   "dom"
  ]
 }
}

14 行

"types" : ["lodash"],

在 typeroots 新增 types ,在陣列中加入 lodash ,表示 typescript 在編譯時會使用剛剛安裝的 lodash type 定義檔。

import lodash
app.component.ts
import {component, oninit} from '@angular/core';
import * as _ from 'lodash';
@component({
 selector: 'app-root',
 templateurl: './app.component.html',
 styleurls: ['./app.component.css']
})
export class appcomponent implements oninit {
 title = 'app';
 ngoninit(): void {
  const scores: number[] = [100, 99, 98];
  _.remove(scores, 2);
  scores.foreach((score) => console.log(score));
 }
}

第 2 行

import * as _ from 'lodash';

載入 lodash 。

因為 lodash 習慣以 _ 使用,因此 import 時特別取別名為 _

webstorm 對於 angular 內建的 api,都可以自動 import,但對於 javascript 的 package,目前 webstorm 還沒有辦法自動 import,需手動載入

15 行

_.remove(scores, 2);

陣列的移除元素一直是 javascript 比較麻煩的部分,透過 lodash 的 remove() ,可以很簡單的使用。

conclusion

實務上若有 angular 版本的 package,當然優先使用;若遇到必須使用 javascript package 不可的場合,除了安裝 package 外,還要安裝 type 定義檔,並且在 tsconfig.json 設定,如此才可以在 angular 正確使用並通過編譯

sample code

完整的範例可以在我的github 上找到

总结

以上所述是小编给大家介绍的在 angular中 使用 lodash 的方法,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网