本文介绍了在Angular 4中使用lodash的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我以前在Angular 4应用程序中使用过lodash,只需将其导入并按如下所示使用它:

I have previously used lodash in my Angular 4 application by simply importing it and using it as shown here:

import lodash from 'lodash';

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

}

我再次尝试类似地使用lodash,但是却收到一个错误,表明lodash是未定义的.

I am once again trying to use lodash similarly but am getting an error that lodash is undefined.

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 (包含类型定义):

First you need to install the packages lodash and @types/lodash (contains type definitions):

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

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

Then you can use lodash e.g. with import * as _ from 'lodash'; and further do _.indexOf([1, 2, 1, 2], 2);

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

You could also do import * as _isEmpty from 'lodash/isEmpty'; (thanks to joshrathke) or import {isEmpty} from 'lodash';

这篇关于在Angular 4中使用lodash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 18:24