在Angular 4中使用lodash

时间:2018-02-16 23:10:01

标签: angular lodash

我之前在Angular 4应用程序中使用了lodash,只需导入并使用它,如下所示:

import lodash from 'lodash';

public getSubtotal() : number {
  return lodash.sumBy(this.cartItems, function(item) {        
    return item.product.price * item.item.quantity;
  })

}

我再一次尝试使用lodash,但是我得到的错误是lodash未定义。

import lodash from 'lodash';

lodash.indexOf([1, 2, 1, 2], 2);

我收到以下错误:

ERROR TypeError: Cannot read property 'indexOf' of undefined
at CustomizeComponent.showTopping (customize.component.ts:39)
at Object.eval [as updateDirectives] (CustomizeComponent.html:285)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:14638)
at checkAndUpdateView (core.js:13785)
at callViewAction (core.js:14136)
at execComponentViewsAction (core.js:14068)
at checkAndUpdateView (core.js:13791)
at callViewAction (core.js:14136)
at execEmbeddedViewsAction (core.js:14094)
at checkAndUpdateView (core.js:13786)

2 个答案:

答案 0 :(得分:12)

首先,您需要安装包lodash@types/lodash(包含类型定义):

npm i lodash
npm i --save-dev @types/lodash

然后你可以使用lodash,例如使用import * as _ from 'lodash';并进一步执行_.indexOf([1, 2, 1, 2], 2);

你也可以import * as _isEmpty from 'lodash/isEmpty';(感谢joshrathke)或import {isEmpty} from 'lodash';

答案 1 :(得分:2)

在角内导入lodash或任何JavaScript库:

步骤1::安装libarary(lodash)

npm i --save lodash

步骤2::将其导入组件并使用。

按以下步骤导入它:

import 'lodash';

declare var _:any;

import * as _ from 'lodash';

第3步:为Lo-Dash安装类型定义(可选)

npm install --save-dev @types/lodash

如果仍有疑问,请参见示例

import { Component, OnInit } from '@angular/core';
// import * as _ from 'lodash';
import 'lodash';

declare var _:any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'test-lodash';

  ngOnInit() {
    console.log(_.chunk(['a', 'b', 'c', 'd'], 2)); //lodash function
    console.log(_.indexOf([1, 2, 1, 2], 2)); //lodash function
  }

}