Using lodash in Angular 4

*爱你&永不变心* 提交于 2020-02-13 08:01:56

问题


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;
  })

}

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);

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)

回答1:


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

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

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

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




回答2:


Importing lodash or any javascript library inside angular:

step-1: Install the libarary(lodash)

npm i --save lodash

step-2: import it inside the component and use it.

import it as follow:

import 'lodash';

declare var _:any;

or

import * as _ from 'lodash';

Step-3: Install type definitions for Lo-Dash (it's optional)

npm install --save-dev @types/lodash

see the example if you still have doubts

import { Component, OnInit } from '@angular/core';
// import * as _ from 'lodash';
import 'lodash';

declare var _:any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'test-lodash';

  ngOnInit() {
    console.log(_.chunk(['a', 'b', 'c', 'd'], 2)); //lodash function
    console.log(_.indexOf([1, 2, 1, 2], 2)); //lodash function
  }

}


来源:https://stackoverflow.com/questions/48836140/using-lodash-in-angular-4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!