要从Firebase数据库中检索当前用户的数据,您需要执行以下步骤:
以下是一个使用Firebase Realtime Database的示例代码:
// Import Firebase SDK
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/database';
// Your web app's Firebase configuration
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",
appId: "YOUR_APP_ID"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Sign in the user
firebase.auth().signInWithEmailAndPassword(email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
console.log(user.uid); // Get the user's UID
})
.catch((error) => {
console.error('Error signing in:', error);
});
// Get a reference to the database service
const database = firebase.database();
// Get a reference to the current user's data
const userRef = database.ref(`users/${user.uid}`);
// Read the data at this location
userRef.once('value', (snapshot) => {
const userData = snapshot.val();
console.log(userData);
}, (error) => {
console.error('Error reading data:', error);
});
如果您使用的是Firestore,步骤类似,但API略有不同:
// Import Firebase SDK
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Sign in the user
firebase.auth().signInWithEmailAndPassword(email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
console.log(user.uid); // Get the user's UID
})
.catch((error) => {
console.error('Error signing in:', error);
});
// Get a reference to the Firestore database
const db = firebase.firestore();
// Get a reference to the current user's data
const userRef = db.collection('users').doc(user.uid);
// Read the data at this location
userRef.get().then((doc) => {
if (doc.exists) {
const userData = doc.data();
console.log(userData);
} else {
console.log('No such document!');
}
}).catch((error) => {
console.error('Error reading data:', error);
});
通过这些步骤,您可以从Firebase数据库中检索当前用户的数据。确保您已经正确设置了Firebase,并且用户已经登录。
领取专属 10元无门槛券
手把手带您无忧上云