在Angular 4中使用lodash

28

我之前在我的 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,但出现了未定义的错误。

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)
1个回答

59

首先,您需要安装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';


7
值得一提的是,仅直接导入您需要的模块可以使您的构建文件明显变小。相对于 Lodash 库而言,这种变化是显著的 :)import * as _indexOf from 'lodash/indexOf'; - joshrathke
1
@joshrathke 这是个好观点。我会编辑我的答案来补充这一点。 - pzaenger
完美地工作了。谢谢。 - koque
2
@pzaenger import * as _isEmpty from 'lodash/isEmpty'; 不起作用。显示 此模块只能使用 ECMAScript... - Rich
2
@Rich - 你可以试试这个 - import { isEmpty as _isEmpty } from 'lodash' - thiag0
基于@joshrathke建议的导入样式和答案中的括号语法,我最喜欢的方法是import { isEmpty as _isEmpty, cloneDeep as _cloneDeep } from 'lodash';。这是两全其美的选择。您可以重命名lodash模块,而且不需要了解lodash的内部结构。我展示了多个lodash模块以供参考:-)。编辑:刚看到@thiag0的答案,这也是一样的lol。好吧,至少这表明了导入多个模块¯\(ツ)/¯。 - mogelbuster

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接