<function name>错误:FirebaseError:Firebase:没有创建Firebase应用程序“[DEFAULT]” - 首先调用initializeApp()(应用程序/无应用程序)

问题描述 投票:0回答:1

我正在使用 firebase 本地模拟构建一个网络应用程序。我可以使用 Firebase 身份验证,但在尝试查询数据库时遇到没有意义的错误。

以下是相关测试代码:

import { initializeApp, getApps } from 'firebase/app';
import { getAuth, connectAuthEmulator, signInWithEmailAndPassword, signOut } from 'firebase/auth';
import { executeQuery, getDataConnect, connectDataConnectEmulator } from 'firebase/data-connect';
import { getStudentByemail, connectorConfig } from '@firebasegen/default-connector';

let fbApp = null;
let dConnect = null;
let fbInitialized = false;

async function fetchFbConfig() {
  try {
    const response = await fetch('http://localhost:5001/<project-name>/us-central1/getApiKey');
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const fbConfig = await response.json();
    return fbConfig;
  } catch (error) {
    console.error('Error fetching Firebase config:', error);
  }
}

// Initialize Firebase with the fetched config
fetchFbConfig()
  .then(fbConfig => {
    if (!fbConfig) throw new Error('Failed to fetch Firebase config');

    // Initialize Firebase only if it hasn't been initialized already
    if (!getApps().length) {
      fbApp = initializeApp(fbConfig);
      const auth = getAuth(fbApp);

      connectAuthEmulator(auth, "http://127.0.0.1:9099");

          console.log('Initializing DataConnect...');
          dConnect = getDataConnect(connectorConfig);

          if (!dConnect) throw new Error('dataConnect not initialized');

          connectDataConnectEmulator(dConnect, 'localhost', 9399);
          dConnect.setInitialized();
          fbInitialized = true;

          window.GetStudentByemail = async function(_email) {
            if (!fbInitialized || !dConnect) {
              throw new Error('Firebase/DataConnect not initialized');
            }
            console.log('GetStudentByemail function activated with ', _email);
            try {
              const query = getStudentByemail({ email: _email });
              console.log('Query:', query);
              const qryRef = await executeQuery(dConnect, query);
              
              return new Promise((resolve, reject) => {
                qryRef.onSnapshot(
                  snapshot => resolve(snapshot.data()),
                  error => reject(error)
                );
              });
            } catch (error) {
              console.error('GetStudentByemail error:', error);
              throw error;
            }
          };
          
          window.signInUser = function(email, password, callback) {
            if (!fbInitialized) {
              console.error('Firebase not initialized');
              callback(false);
              return;
            }

            signInWithEmailAndPassword(auth, email, password)
              .then((userCredential) => {
                if (userCredential.user.emailVerified) {
                  console.log('User signed in:', userCredential.user);
                  callback(true);
                } else {
                  console.error('Email not verified.');
                  signOut(auth);
                  callback(false);
                }
              })
              .catch((error) => {
                console.error('Error signing in:', error.code, error.message);
                callback(false);
              });
          };

          window.signInUser("<email>", "<password>", async function(isLoggedIn) {
            if (isLoggedIn) {
              try {
                  console.log('fetchStudentData function activated with ', "<email>");
                  const studentData = await window.GetStudentByemail("<email>");
                  console.log('Fetched student data:', studentData);
                } catch (error) {
                  console.error('Error fetching student data:', error);
                }
            } else {
              console.log('User not logged in.');
            }
          });
    }
  })
  .catch((error) => {
    console.error('Error initializing Firebase:', error);
  });

控制台日志为:

Initializing DataConnect... index.js:35:18
User signed in: Object <> index.js:76:26
fetchStudentData function activated with  <email> index.js:93:26
GetStudentByemail function activated with  <email> index.js:48:20
GetStudentByemail error: FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call initializeApp() first (app/no-app).

线上抛出错误

const query = getStudentByemail({ email: _email });

在 GetStudentByemail 函数中。从 VSCode 中的数据连接执行终端调用时,查询 getStudentByemail 会给出正确的响应,并且在 SDK 中存在且正确。

显然,Firebase 应用程序是因为用户已登录而创建的,并且 dataConnect 也已正确初始化,因此唯一有意义的是 Promise 的执行是否先于 Firebase 应用程序的初始化。我读过有关从不同队列(微任务)执行的承诺可能会导致此错误,但我迷失了并抓住了救命稻草,即使是这种情况我也不知道如何解决。

请原谅任何不正确的术语,我不是程序员,所以我对此非常不了解。

任何帮助将不胜感激。

javascript firebase firebase-data-connect
1个回答
0
投票

我以前没有使用过Data Connect,但在我看来,你应该导入

getStudentByemailRef
而不是
getStudentByemail
。 “ref”版本使用
executeQuery
执行,而“non-ref”版本(“根据文档的操作快捷函数”)只是您直接调用来执行查询的函数。 我根据我在文档中看到的内容做出这个猜测。

© www.soinside.com 2019 - 2024. All rights reserved.