javascript - 当输入为 null 时,ngbtypeahead 函数返回 TypeError

标签 javascript angular typescript ng-bootstrap

我在 Angular 8 项目中使用 ng-bootstrap 中的 typeahead 元素,https://ng-bootstrap.github.io/#/components/typeahead/examples 。我正在使用库示例中给出的函数,但如果我的输入之一为空,我会收到错误。

我的组件类中有一个变量,它是用函数构建的:

searchAutofill = (text$: Observable<string>) =>
    text$.pipe(
      debounceTime(200),
      distinctUntilChanged(),
      map(term => term.length < 1 ? []
        : this.option.filter(v => v.toLowerCase().indexOf(term.toLowerCase()) > -1).slice(0, 15))
    )

option是一个字符串数组,例如:

[
    "tom",
    "bob",
    "foo",
    "emma",
    null,
    "john",
    "hello",
    "example",

当函数达到 null 值时,它返回ERROR TypeError: "v is null"。如何更改代码以接受/忽略空值?

最佳答案

是的,因为您尝试对“null”值执行 String 方法。

所以在这里v.toLowerCase()你得到null.toLowerCase()

每当您访问对象的任何属性或方法时,您必须确保该对象是您期望的对象。否则设置一些规则来检查,

在您的情况下,您似乎想检查字符串 v 中是否有一个子字符串保存在 term 变量中。

所以我猜测如果 vnull,您希望返回 false:

filter(v => v && v.toLowerCase().indexOf(term.toLowerCase()) > -1)

附:请注意,这里我只是检查 v 是否不是一个虚假值。您可能需要添加额外的规则来检查它是否是字符串。例如:

typeof v === 'string'

关于javascript - 当输入为 null 时,ngbtypeahead 函数返回 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58804639/

相关文章:

javascript - Gulp 浏览器同步 ENOENT 错误

javascript - 如何在 Chai 中使用 include?

javascript - 通过使用具有相同 id 的多行更改 optionsMenu 中的值来选中复选框

javascript - 如何避免使用 trackBy 函数避免为 nGFor 重建 DOM - Angular Firestore

typescript - AWS CDK - 构造函数参数不匹配

javascript - 选择具有所有相同元素标签的子组

html - 滚动时如何消除空格[固定侧边栏]

css - 组件的 Angular/CSS 动态样式部分

javascript - 使用@nestjs/graphql 使用@ResolveProperty 和@Resolvers 创建嵌套查询

typescript - 使用 Typescript 的 angular2 上的开关按钮