【问题标题】:Angular CLI - Can't use Array.find() within Observable pipe functionAngular CLI - 不能在 Observable 管道函数中使用 Array.find()
【发布时间】:2018-08-22 09:51:59
【问题描述】:

我有以下代码:

import { AbstractControl, ValidationErrors } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import { filter, map, tap} from 'rxjs/operators';


export function valueInCollectionValidator(collection: Observable<any[]>, propertyName: string) {
  return (control: AbstractControl): Observable<ValidationErrors> => {
    return collection.pipe(
      filter(array => array.find(e => e[propertyName] == control.value)),
      map(ok => ok ? undefined : { valueNotInCollection: false }),
    );
  };
}

使用 Angular CLI 的 ng serve 时,出现构建错误:

validators.ts (9,29) 中的错误:类型“{}”上不存在属性“find”。

这是我的 jsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "module": "commonjs",
    "lib": [
      "es2017",
      "dom"
    ]
  }
}

知道为什么这不起作用吗?谢谢!

【问题讨论】:

  • 我真正在寻找的是一种将数组的可观察对象“展平”为单个项目的可观察对象的方法。这可以通过使用 mergeAll() 运算符解决,并在此处回答:stackoverflow.com/questions/42482705/…

标签: angular typescript ecmascript-6 angular-cli


【解决方案1】:

filter 方法自动接收每个数组元素。因此,实际上,您在 filter 方法中引用的 array 是数组 collection 的一个元素,在您的情况下是 object

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 2019-06-02
    • 2021-05-13
    • 1970-01-01
    相关资源
    最近更新 更多