Using lodash in Angular 4

I previously used lodash in my Angular 4 application, simply importing it and using it as shown below:

import lodash from 'lodash';

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

}

I try to use lodash again, but I get the lodash undefined error message.

import lodash from 'lodash';

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

I get the following error:

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)
+4
source share
1 answer

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

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

Then you can use lodash, for example. c import * as _ from 'lodash';and beyond_.indexOf([1, 2, 1, 2], 2);

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

+3
source

Source: https://habr.com/ru/post/1693759/


All Articles