Ionic3调用AngularFire httpsCallable报Object(...) is not a function错误求助
我来帮你梳理下这个问题,你在Ionic 3里调用Firebase可调用云函数时踩的坑,其实主要是版本兼容性和初始化/调用方式不对导致的,咱们一步步来解决:
首先看你遇到的两个核心错误:
错误1:ERROR TypeError: WEBPACK_IMPORTED_MODULE_5_firebase_functions.functions is not a function
这个问题出在直接用Firebase SDK的写法上,原因很简单:你可能没正确导入firebase/functions模块,或者Firebase App没完成初始化。
错误2:ERROR TypeError: Object(...) is not a function & newGame是对象而非函数
结合你提到的PR,这明显是AngularFire2的版本和Ionic 3不兼容导致的。Ionic 3对应的是Angular 5.x,而较新的AngularFire2版本依赖更高版本的Angular,旧版本的AngularFire2要么没实现httpsCallable,要么实现方式不对,导致返回的不是可调用函数而是对象。
解决方案:分两种情况处理
情况一:使用AngularFire2(推荐,符合Ionic/Angular生态)
安装兼容版本的依赖
Ionic 3必须用适配Angular 5的AngularFire2版本,比如5.0.0-rc.11,同时Firebase版本对应到5.x系列:npm install angularfire2@5.0.0-rc.11 firebase@5.12.1 --save正确初始化模块
在AppModule里导入并配置AngularFire和Functions模块:import { NgModule } from '@angular/core'; import { AngularFireModule } from 'angularfire2'; import { AngularFireFunctionsModule } from 'angularfire2/functions'; // 替换成你的Firebase配置 const firebaseConfig = { apiKey: 'YOUR_API_KEY', authDomain: 'YOUR_AUTH_DOMAIN', databaseURL: 'YOUR_DATABASE_URL', projectId: 'YOUR_PROJECT_ID', storageBucket: 'YOUR_STORAGE_BUCKET', messagingSenderId: 'YOUR_MESSAGING_SENDER_ID' }; @NgModule({ imports: [ AngularFireModule.initializeApp(firebaseConfig), AngularFireFunctionsModule // 必须导入这个模块 ] }) export class AppModule {}正确注入并调用函数
注意!在这个版本的AngularFire2里,httpsCallable返回的是Observable,不是Promise,所以要用subscribe而不是then:import { Component } from '@angular/core'; import { AngularFireFunctions } from 'angularfire2/functions'; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { constructor(private afFunctions: AngularFireFunctions) {} createGame() { // 获取可调用函数引用 const newGame = this.afFunctions.httpsCallable('findCreateGame'); // 调用函数并处理结果 newGame({ /* 这里传你的参数 */ }) .subscribe( result => console.log('调用成功:', result), error => console.error('调用出错:', error) ); } }
情况二:直接使用Firebase SDK
如果不想用AngularFire2,直接用原生Firebase SDK的话,要确保正确导入和初始化:
import * as firebase from 'firebase/app'; // 必须导入functions模块! import 'firebase/functions'; // 初始化Firebase App(如果还没初始化的话) firebase.initializeApp({ /* 你的Firebase配置 */ }); // 获取Functions实例,如果函数部署在非默认区域,要指定区域 const functions = firebase.app().functions('us-central1'); // 获取可调用函数 const newGame = functions.httpsCallable('findCreateGame'); // 调用函数 newGame({}) .then(result => console.log('调用成功:', result)) .catch(error => console.error('调用出错:', error));
为什么你之前的代码能调用但还报错?
你提到const newGame = this.afFunctions.httpsCallable('findCreateGame'); newGame();能成功调用但抛错,是因为错误的版本下,httpsCallable返回的不是标准的可调用函数,而是一个包含调用方法的对象(比如可能需要newGame.call()),但这不是正确的实现,所以必须换兼容的版本才能解决根本问题。
内容的提问来源于stack exchange,提问作者Tristan

