Javascript 在新 API 的两个单独文件中初始化 Firebase 引用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37337080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Initialize Firebase references in two separate files in the new API
提问by Long Sang Chan
I have upgraded to the new API and don't know how to initialize Firebase references in two separate files:
我已升级到新 API,但不知道如何在两个单独的文件中初始化 Firebase 引用:
/* CASE 1 */
// 1st file
var config = {/* ... */};
firebase.initializeApp(config);
var rootRef = firebase.database().ref();
// 2nd file - initialize again
var config = {/* ... */};
firebase.initializeApp(config);
var rootRef = firebase.database().ref();
RESULT: bundle.js:535 Uncaught Error: Firebase App named '[DEFAULT]' already exists.
结果:bundle.js:535 未捕获的错误:名为“[DEFAULT]”的 Firebase 应用已经存在。
/* CASE 2 */
// 1st file
var config = {/* ... */};
firebase.initializeApp(config);
var rootRef = firebase.database().ref();
// 2nd file - don't initialize
var rootRef = firebase.database().ref();
RESULT: bundle.js:529 Uncaught Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp().
结果:bundle.js:529 未捕获错误:未创建 Firebase 应用“[DEFAULT]” - 调用 Firebase App.initializeApp()。
Before the new API I just called
在我刚刚调用的新 API 之前
var myFirebaseRef = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/");
in each file, and it worked okay.
在每个文件中,它工作正常。
回答by lommaj
This is an issue I ran into as well upgrading to the new version of Firebase. You might want two separate firebase apps initialized, like explained in other answers, but I just wanted to use the refs in two different locations in my app and I was getting the same error.
这是我在升级到新版 Firebase 时也遇到的问题。您可能想要初始化两个单独的 firebase 应用程序,如其他答案中所述,但我只想在我的应用程序的两个不同位置使用 refs,但我遇到了相同的错误。
What you need to do for this situation is to create a firebase module for your app that only initializes firebase once, then you import or require it elsewhere in your app.
针对这种情况,您需要做的是为您的应用程序创建一个仅初始化 firebase 一次的 firebase 模块,然后在应用程序的其他地方导入或要求它。
This is pretty simple, here is mine: modules/firebase.js
这很简单,这是我的:modules/firebase.js
import firebase from 'firebase';
var firebaseConfig = {
apiKey: "some-api-key",
authDomain: "some-app.firebaseapp.com",
databaseURL: "https://some-app.firebaseio.com",
storageBucket: "some-app.appspot.com",
};
var FbApp = firebase.initializeApp(firebaseConfig);
module.exports.FBApp = FbApp.database(); //this doesnt have to be database only
And then elsewhere in your application you simply:
然后在您的应用程序的其他地方,您只需:
import FBApp from '/your/module/location'
var messagesRef = FBApp.ref("messages/");
回答by Jaime Gómez
You need to name your different instances (Apps as Firebase calls them); by default you're working with the [DEFAULT]
App, because that's the most common use case, but when you need to work with multiple Apps then you have to add a name when initialising:
您需要为不同的实例命名(Firebase 调用它们的应用程序);默认情况下,您使用的是[DEFAULT]
应用程序,因为这是最常见的用例,但是当您需要使用多个应用程序时,您必须在初始化时添加一个名称:
// Intialize the "[DEFAULT]" App
var mainApp = firebase.intializeApp({ ... });
// Intialize a "Secondary" App
var secondaryApp = firebase.initializeApp({ ... }, "Secondary");
...
mainApp.database().ref("path/to/data").set(value);
secondaryApp.database().ref("path/to/data").set(anotherValue);
You can find a more example scenarios in the updated Initialize multiple appssection of the Add Firebase to your JavaScript Project guide.
您可以在将 Firebase 添加到您的 JavaScript 项目指南的更新后的初始化多个应用部分中找到更多示例场景。
回答by andresk
If you don't have the control over where Firebase will be instantiated, you can do something like this:
如果您无法控制 Firebase 的实例化位置,您可以执行以下操作:
try {
let firApp = firebase.app(applicationName);
return firApp;
} catch (error) {
return firebase.initializeApp({
credential: firebase.credential.cert(firebaseCredentials),
databaseURL: firebaseUrl
}, applicationName);
}
Firebase will try to get the application, if it doesn't exist, then you can initialize it freely.
Firebase 将尝试获取该应用程序,如果它不存在,那么您可以自由地对其进行初始化。
回答by Jeroen Wienk
I made the mistake by importing like this.
我通过像这样导入而犯了错误。
import firebase from 'firebase'
const firebaseConfig = {
apiKey: 'key',
authDomain: 'domain',
databaseURL: 'url',
storageBucket: ''
};
firebase.initializeApp(firebaseConfig);
This worked fine for a few days but when I tried to sign in with custom tokensmy auth object was not changed. I had to refresh the page for it to update so I could make certain calls to the database which were protected by my own auth credentials rules.
这几天工作正常,但是当我尝试使用自定义令牌登录时,我的身份验证对象没有改变。我必须刷新页面才能更新,以便我可以对受我自己的身份验证凭据规则保护的数据库进行某些调用。
".read": "$uid === auth.uid || auth.isAdmin === true || auth.isTeacher === true",
When I changed my imports to this it worked again.
当我将导入更改为此时,它再次起作用。
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/database';
const firebaseConfig = {
apiKey: 'key',
authDomain: 'domain',
databaseURL: 'url',
storageBucket: ''
};
firebase.initializeApp(firebaseConfig);
Then whenever I need to use Firebase in a certain module I import this(notice the import from firebase/app instead of firebase):
然后每当我需要在某个模块中使用 Firebase 时,我都会导入它(注意从 firebase/app 而不是 firebase 的导入):
import firebase from 'firebase/app';
And talk to certain services like so:
并像这样与某些服务交谈:
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// Authenticated.
} else {
// Logged out.
}
});
firebase.database().ref('myref').once('value').then((snapshot) => {
// do stuff with the snapshot
});
回答by hayden
To make multiple instances using new firebase.initializeApp()
, you need a second parameter for the firebase constructor:
要使用 制作多个实例new firebase.initializeApp()
,您需要为 firebase 构造函数提供第二个参数:
firebase.initializeApp( {}, "second parameter" );
Compare it to the old way to generate multiple instances where
将其与生成多个实例的旧方法进行比较,其中
new Firebase.Context()
is the second parameter:
是第二个参数:
new Firebase('', new Firebase.Context() );