【问题标题】:lodash find not working in Angular projectlodash 发现在 Angular 项目中不起作用
【发布时间】:2019-08-16 09:39:04
【问题描述】:
npm install lodash
npm install @types/lodash

ng serve
import { find, upperCase } from 'lodash';

console.log(upperCase('test')); // 'TEST'
console.log(find(items, ['id', id])) // TypeError: "Object(...)(...) is undefined"

我尝试使用 import * as _ from 'lodash' 代替或不使用 _.matchesProperty iteratee 速记但没有任何效果。

我找不到任何教程提到在 Angular 项目中使用 lodash 的任何其他步骤。

Angular CLI: 8.2.2
Node: 10.14.1
OS: win32 x64
Angular: 8.2.2

Package                           Version
-----------------------------------------------------------
typescript                        3.5.3
webpack                           4.38.0

【问题讨论】:

  • find(items, ['id', id]),但 items 未定义...
  • upperCase('test') // 'TEST',真的,有时候,我想知道为什么人们加载库只是为了执行"test".toUpperCase()...
  • @JeremyThille 除非有什么诡异的事情发生,否则items 应该被定义(console.log 以上find 显示Array [ {…}, {…} ])。 upperCase 只是 lodash 至少部分工作的演示。
  • 我刚试过const items = [{id:1},{id:2}]; console.log( find(items, ['id', 2]) ),输出是{ id : 2 }。看起来问题是您的输入数据
  • @JeremyThille 你是对的。我尝试了一个 for 循环,发现 ID 不匹配。当我使用 _.find 时,关于一些未定义的 Webpack 导入的早期错误消息让我大吃一惊。

标签: javascript angular typescript lodash


【解决方案1】:

我们正在使用 lodash-es 包,通过它您可以导入单个函数。

安装

yarn add lodash-es @types/lodash-es
// or
npm --save lodash-es @types/lodash-es

使用

import isArray from 'lodash-es/isArray';

const res = isArray(somevar);

【讨论】:

    【解决方案2】:

    按照以下步骤将 loadash 与 Angular 一起使用:

    1. 安装负载

      npm install --save lodash

    2. 安装类型

      $ npm install --save-dev @types/lodash

    3. 导入负载

      import * as _ from "lodash";

      或者

      import _ from "lodash";

    将示例运行为:

    const items =[{id: 10, name: "Alex" }, {id: 20, name: "Jane"}];
    console.log(_.find(items, ['id', 10]));
    

    上述程序的输出将是:

    {id: 10, name: "Alex" }
    

    【讨论】:

      猜你喜欢
      • 2018-08-14
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      • 2019-05-29
      • 2020-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多