你可能是在应用程序初始化之前调用firebase
。所有对firebase
的调用必须在.initializeApp();
之后进行。
firebase.initializeApp(config);
var db = firebase.firestore();
如果您正在使用Angular,这里有一个解决方案。
完整的教程来源链接
在@ NgModule之前使用initializeApp
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { environment } from 'src/environments/environment';
import { AuthenticateService } from './services/authentication.service';
import { AngularFireAuthModule } from '@angular/fire/auth';
import * as firebase from 'firebase';
firebase.initializeApp(environment.firebase);
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [
BrowserModule,
IonicModule.forRoot(),
AppRoutingModule,
AngularFireAuthModule
],
providers: [
StatusBar,
SplashScreen,
AuthenticateService,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule {}
如果您正在使用 React Native,那么如果您没有正确配置native侧,则也会发生此错误。
文档在这里:https://rnfirebase.io/
Android
首先,请下载google-services.json
文件并将其放置在您的项目中的以下位置:/android/app/google-services.json
。
然后,在您的/android/build.gradle
中添加google-services插件作为依赖项。
buildscript {
dependencies {
// ... other dependencies
classpath 'com.google.gms:google-services:4.3.10'
// Add me --- /\
}
}
最后,通过将以下内容添加到您的/android/app/build.gradle
中来执行该插件
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services' // <- Add this line
iOS
首先,通过xcode将GoogleService-Info.plist
文件添加到项目中。确保它出现在构建阶段中,这样您就知道它已经添加到项目中而不仅仅是文件夹中。
然后,打开/ios/{projectName}/AppDelegate.m
文件,并添加以下内容:
在文件顶部导入Firebase SDK:
#import <Firebase.h>
在现有的didFinishLaunchingWithOptions方法中,将以下内容添加到方法顶部:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Add me --- \/
[FIRApp configure];
// Add me --- /\
// ...
}
如果您正在使用Dart和Flutter
4.在main()中添加 async
按照我的代码操作
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
var fsconnect = FirebaseFirestore.instance;
myget() async {
var d = await fsconnect.collection("students").get();
// print(d.docs[0].data());
for (var i in d.docs) {
print(i.data());
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Firebase Firestore App'),
),
body: Column(
children: <Widget>[
RaisedButton(
child: Text('send data'),
onPressed: () {
fsconnect.collection("students").add({
'name': 'sarah',
'title': 'xyz',
'email': 'sarah@gmail.com',
});
print("send ..");
},
),
RaisedButton(
child: Text('get data'),
onPressed: () {
myget();
print("get data ...");
},
)
],
),
));
}
}
我在遵循Firebase在线指南(链接)时遇到了类似的问题。
“初始化多个应用程序”的章节标题有误导性,因为该标题下的第一个示例实际上展示了如何初始化单个默认应用程序。以下是该示例:
// Initialize the default app
var defaultApp = admin.initializeApp(defaultAppConfig);
console.log(defaultApp.name); // "[DEFAULT]"
// Retrieve services via the defaultApp variable...
var defaultAuth = defaultApp.auth();
var defaultDatabase = defaultApp.database();
// ... or use the equivalent shorthand notation
defaultAuth = admin.auth();
defaultDatabase = admin.database();
AngularFireModule.initializeApp(firebaseConfig, 'reservas')
如果我删除第二个参数,它就能正常工作:
AngularFireModule.initializeApp(firebaseConfig)
[DEFAULT]
,因此是“默认应用程序”。这对您很重要的原因可能是代码可以通过例如firebase.firestore()
隐式使用默认值,而使用自定义“app”(第一个)时,必须传递返回值,“app句柄”。我两种方式都使用。主Web应用程序使用默认值,库中使用命名变量。 - akauppi这可能不是最佳答案,但我必须像下面这样使用管理员和Firebase来初始化应用程序。 我使用管理员来完成自己的目的,也使用Firebase。
const firebase = require("firebase");
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
firebase.initializeApp(functions.config().firebase);
// Get the Auth service for the default app
var authService = firebase.auth();
function createUserWithEmailAndPassword(request, response) {
const email = request.query.email;
const password = request.query.password;
if (!email) {
response.send("query.email is required.");
return;
}
if (!password) {
response.send("query.password is required.");
return;
}
return authService.createUserWithEmailAndPassword(email, password)
.then(success => {
let responseJson = JSON.stringify(success);
console.log("createUserWithEmailAndPassword.responseJson", responseJson);
response.send(responseJson);
})
.catch(error => {
let errorJson = JSON.stringify(error);
console.log("createUserWithEmailAndPassword.errorJson", errorJson);
response.send(errorJson);
});
}
如果你正在使用React Native并且开发IOS应用,那么我认为你可能忘记了链接Firebase模块的步骤。
请按照以下步骤进行:
打开/ios/{projectName}/AppDelegate.m
文件,并添加以下内容:
在文件顶部导入Firebase SDK:
#import <Firebase.h>
在您现有的didFinishLaunchingWithOptions
方法中,将以下内容添加到该方法的顶部:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Add this --- \/
if ([FIRApp defaultApp] == nil) {
[FIRApp configure];
}
// Add me --- /\
// ...
}
Flutter Web
对于我来说,当我以“release”模式运行我的应用程序时出现了错误。
flutter run -d chrome --release
并且当我在Firebase托管上部署应用程序时也出现了错误。
firebase deploy
解决方案
由于我在index.html中初始化了Firebase,所以我必须改变firebase和main.dart.js的实现顺序。
<script>
var firebaseConfig = {
apiKey: "xxxxxxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxx.firebaseapp.com",
databaseURL: "https://xxxxxxxxxx.firebaseio.com",
projectId: "xxxxxxxxxxx",
storageBucket: "xxxxxxxx.appspot.com",
messagingSenderId: "xxxxxxxxxxx",
appId: "1:xxxxxxxxxx:web:xxxxxxxxxxxxx",
measurementId: "G-xxxxxxxxx"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
//moved below firebase init
<script src="main.dart.js" type="application/javascript"></script>
这个答案可能已经在别处给出,但这是我对这个错误的看法,这个错误可能由多种原因引起:
firebase.apps.app()
在初始化默认应用程序之前被调用。这段代码基本上返回默认应用程序实例。由于它不存在,因此会出现错误。{firebaseClient,dbClient,authClient,storageClient}
,其中单独的服务被定义为const dbClient = firebaseClient.firestore(); ...
。 - arunmenon
import firebase from '@react-native-firebase/app';
然后import "@react-native-firebase/database"
,但它不起作用。 - Stephen Phillipsfirebase
导入),而在另一个模块中,我意外地从firebase
导入,而不是从我的(已初始化的)./firebase
。 - Ruben9922