angular - 在 Angular 4 中使用 lodash

标签 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)

最佳答案

首先你需要安装软件包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';

关于angular - 在 Angular 4 中使用 lodash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48836140/

相关文章:

css - angular - 单击 flexbox 网格单元以全宽扩展下方区域

ios - null 不是对象(评估 '__gCrWeb.form.wasEditedByUser.set' )

node.js - 使用 Node 转换来自 Azure 表存储的响应

JavaScript:无法获取对象的值

JavaScript 在数组中找到第一个 <= 给定数字的数字

javascript - 我如何在 Lodash 中执行此操作?

c# - TypeScript:相当于 C# 的用于扩展类的通用类型约束?

Angular 2复选框选中所有

angular - 如何在angular2中使用组件名称动态加载组件?

javascript - 使用 Lodash 比较、匹配和过滤两个对象