You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular5中使用ng-bootstrap typeahead报错:TypeError: Object(...) is not a function

解决Angular5中使用ng-bootstrap Typeahead的linkToTypeahead功能时出现的ERROR TypeError: Object(...) is not a function问题

这个错误我之前帮好几个开发者排查过,大概率是版本不兼容导致的——Angular5和ng-bootstrap、RxJS的版本对应关系很严格,错配就会触发这类奇怪的构造函数错误。下面一步步帮你解决:

1. 先确认核心版本匹配

Angular 5只能搭配ng-bootstrap 1.x系列的版本,如果你装了2.0.0及以上的ng-bootstrap,就会因为它依赖的RxJS特性和Angular5自带的RxJS版本冲突,直接在NgbTypeahead初始化时报错。

检查并调整版本

打开你的package.json,找@ng-bootstrap/ng-bootstrap的版本号,如果是>=2.0.0,立刻降级:

# 卸载不兼容的版本
npm uninstall @ng-bootstrap/ng-bootstrap
# 安装Angular5兼容的1.x最新版
npm install @ng-bootstrap/ng-bootstrap@1.x --save

2. 同步RxJS版本

Angular5默认配套的是RxJS 5.5.x系列,如果之前升级过RxJS到6.x,也会导致这个错误(RxJS6的导入方式和API都变了,ng-bootstrap 1.x不支持)。同样检查package.json里的rxjs版本,不对的话降级:

npm uninstall rxjs
npm install rxjs@5.5.11 --save

3. 确保模块导入和使用正确

模块导入

在你的应用模块(比如app.module.ts)或者对应功能模块里,正确导入NgbTypeaheadModule:

import { NgbTypeaheadModule } from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  imports: [
    // ...其他已导入的模块
    NgbTypeaheadModule
  ]
})
export class AppModule { }

linkToTypeahead的正确用法

模板里使用routerLink实现跳转的示例(注意要搭配resultTemplate自定义结果模板):

<input 
  type="text" 
  [(ngModel)]="selectedItem" 
  [ngbTypeahead]="searchItems" 
  [resultTemplate]="itemTemplate"
/>

<!-- 自定义结果模板,用routerLink实现跳转 -->
<ng-template #itemTemplate let-item="result">
  <a [routerLink]="['/your-path', item.id]">{{ item.name }}</a>
</ng-template>

对应的组件类里,搜索函数要返回正确的Observable(RxJS5.5+用pipe组合操作符):

import { Observable } from 'rxjs/Observable';
import { debounceTime, distinctUntilChanged, map } from 'rxjs/operators';

// 示例数据源
private items = [
  { id: 1, name: 'Item 1' },
  { id: 2, name: 'Item 2' },
  { id: 3, name: 'Item 3' }
];

// 搜索函数
searchItems = (text$: Observable<string>) =>
  text$.pipe(
    debounceTime(200),
    distinctUntilChanged(),
    map(term => {
      if (term.length < 2) return [];
      return this.items.filter(item => 
        item.name.toLowerCase().includes(term.toLowerCase())
      ).slice(0, 10);
    })
  );

最后验证

执行npm install更新依赖,然后重启开发服务器,应该就能正常使用typeahead的跳转功能了。

内容的提问来源于stack exchange,提问作者somaba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:31:32