【问题标题】:Using lodash in Angular 4在 Angular 4 中使用 lodash
【发布时间】:2018-02-16 23:10:00
【问题描述】:

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

【问题讨论】:

    标签: angular lodash


    【解决方案1】:

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

    【讨论】:

    • 直接导入您需要的模块可以使您的构建显着更小。重要的是,相对于 Lodash 库 :) `import * as _indexOf from 'lodash/indexOf';
    • @joshrathke 这是一个很好的观点。我将编辑我的答案以添加这一点。
    • 完美运行。谢谢。
    • @pzaenger import * as _isEmpty from 'lodash/isEmpty'; 不起作用。说This module can only be referenced with ECMAScript...
    • @Rich - 试试这个 - import { isEmpty as _isEmpty } from 'lodash'
    【解决方案2】:

    在 angular 中导入 lodash 或任何 javascript 库:

    第 1 步: 安装库(lodash)

    npm i --save lodash
    

    第 2 步: 将其导入到组件中并使用它。

    如下导入:

    import 'lodash';
    
    declare var _:any;
    

    import * as _ from 'lodash';
    

    第 3 步:为 Lo-Dash 安装类型定义(可选)

    npm install --save-dev @types/lodash
    

    如果您仍有疑问,请查看示例

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-07
      • 2018-07-03
      • 2021-05-08
      • 1970-01-01
      相关资源
      最近更新 更多