使用Firebase 9.17.1搭配GeoFire时遇TypeError: t.split is not a function问题
问题解决:Firebase 9.17.1 + GeoFire 6.0.0 出现
TypeError: t.split is not a function 问题根源
- GeoFire初始化参数类型错误:GeoFire 6.0.0要求传入Firebase 9的
Database实例(getDatabase(app)返回的对象),但你传入的是DatabaseReference(ref(getDatabase(app))生成的根引用),导致GeoFire内部处理路径时调用split方法失败。 - 不必要的
await使用:new GeoFire()是同步构造函数,无需用await包裹,这会干扰实例初始化逻辑。 - 混用Firebase API风格:构造函数同时使用旧命名空间API(
firebase.app().database())和新模块化API(initializeApp),引发实例冲突。
修复步骤
1. 修正DatabaseHelper构造函数
移除冗余的旧风格代码,统一使用模块化API,保存Database实例而非DatabaseReference:
class DatabaseHelper { private db: Database; private app; constructor(){ this.app = initializeApp({ apiKey: 'censored', appId: 'censored', databaseURL: 'censored', storageBucket: 'censored' }); this.db = getDatabase(this.app); // 保存Database实例 }
2. 修正GeoFire初始化逻辑
移除多余的await,传入正确的Database实例:
public async addDataToGeofire(){ // 移除await,传入Database实例初始化GeoFire const geoFire = new GeoFire(this.db); const requestId = "-NP4heZ1yLXk96HiScqH"; const latitude = 45.502686; const longitude = 15.0655181; await geoFire.set(requestId, [latitude, longitude]) .then(() => { console.log(`Coordinates successfully added to the key: ${requestId}`); }) .catch((error) => { console.error(`An error occurred while adding the coordinate: ${error}`); }); } public async getDataFromGeofire(){ // 移除await,传入Database实例初始化GeoFire const geoFire = new GeoFire(this.db); await geoFire.get("-NP4heZ1yLXk96HiScqH").then(function(location) { if (location === null) { console.log("Provided key is not in GeoFire"); } else { console.log("Provided key has a location of " + location); } }, function(error) { console.log("Error: " + error); }); const geoQuery = geoFire.query({ center: [47, 19], radius: 1000 }); const onReadyRegistration = geoQuery.on("ready", () => { console.log("GeoQuery has loaded and fired all other events for initial data"); }); }
3. 移除冗余代码
删除构造函数中无用的this.database = firebase.app().database('censored');语句,避免多实例冲突。
额外说明
如果需要将GeoFire数据存储在数据库的指定子路径,可传入该路径的DatabaseReference初始化GeoFire,示例:
const geoRef = ref(this.db, "geodata"); // 指定子路径 const geoFire = new GeoFire(geoRef);
内容的提问来源于stack exchange,提问作者Farkas Richárd
相关产品推荐
相关产品推荐

