我以前在我的 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/