Angular 2连接Firebase数据库报错:TypeError: Object(...) is not a function
TypeError: Object(...) is not a function问题 Hey there! Let's break down what's going wrong with your code and get it fixed up quickly.
错误原因
核心问题是Firebase版本不匹配:你现在安装的是Firebase v9+版本,而你的Udemy教程大概率是基于v8或更早版本录制的。
Firebase v9+全面切换为模块化API设计(目的是优化打包体积、支持树摇),而旧版本采用的是命名空间式API。你按照新的模块化方式从firebase/app导入了database,但却想用旧版本firebase.database()的函数调用方式来使用它——但在v9+里,database已经不是可调用的函数了,这就导致了报错。
错误含义
TypeError: Object(...) is not a function这个错误的意思很直白:你把一个不是函数的东西当成函数来调用了。具体到你的代码里,database()试图把导入的database值当作函数执行,但它在v9+的SDK里只是一个普通对象(或非可调用的导出模块),自然会触发错误。
修复方法
你有两种可行的修复方案:
选项1:使用Firebase v9+的模块化API(推荐)
这是Firebase官方主推的现代写法,性能更优且能适配未来的更新。调整代码如下:
import { Component } from '@angular/core'; import { initializeApp } from 'firebase/app'; // 导入数据库相关的模块化方法 import { getDatabase, ref, onValue } from 'firebase/database'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app works!'; constructor() { // Firebase配置保持不变 const config = { apiKey: "AIzaSyAkgFXyAr8UeD9NPM2zU3J32CR_NvaBYHc", authDomain: "final-project-recording-bb15d.firebaseapp.com", databaseURL: "https://final-project-recording-bb15d.firebaseio.com", projectId: "final-project-recording-bb15d", storageBucket: "final-project-recording-bb15d.appspot.com", messagingSenderId: "295297957366" }; const app = initializeApp(config); // 获取数据库实例 const db = getDatabase(app); // 创建指向testArray节点的引用 const rootRef = ref(db, 'testArray'); // 使用新的onValue方法监听数据变化 onValue(rootRef, (snap) => { console.log(snap.val()); }); } }
选项2:启用Firebase兼容模式(贴合教程写法)
如果你想尽量沿用教程里的代码结构,不想做太多改动,可以使用Firebase的兼容层,它允许你在v9+环境下继续使用旧的命名空间式API:
import { Component } from '@angular/core'; // 导入兼容版的Firebase模块 import { database, initializeApp } from 'firebase/compat/app'; import 'firebase/compat/database'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app works!'; constructor() { const config = { apiKey: "AIzaSyAkgFXyAr8UeD9NPM2zU3J32CR_NvaBYHc", authDomain: "final-project-recording-bb15d.firebaseapp.com", databaseURL: "https://final-project-recording-bb15d.firebaseio.com", projectId: "final-project-recording-bb15d", storageBucket: "final-project-recording-bb15d.appspot.com", messagingSenderId: "295297957366" }; initializeApp(config); // 原来的代码现在可以通过兼容层正常运行 const root = database().ref('testArray'); root.on('value', function(snap) { console.log(snap.val()); }); } }
小提示:兼容层虽然方便适配旧教程,但模块化API才是Firebase的长期标准,如果你打算长期使用Firebase,建议优先学习模块化写法。
内容的提问来源于stack exchange,提问作者AndreaNobili

