Firebase.initializeApp callback / promise?

This is my web page.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Calcolo Diliuzioni</title>

    </head>
    <body>

        <h1>My app</h1>

        <!-- Libreria per gestire l'autenticazione con google -->
        <script src="https://apis.google.com/js/platform.js" async defer></script>

        <!-- Firebae config -->
        <script src="https://www.gstatic.com/firebasejs/live/3.0/firebase.js"></script>
        <script>
        // Initialize Firebase
        var config = {
        apiKey: "",
        authDomain: "",
        databaseURL: "",
        storageBucket: "",
        };
        firebase.initializeApp(config);
        </script>

        <script type="text/javascript">
            var user = firebase.auth().currentUser;
            if (user) {
                console.log(user);
            } else {
                console.log(user);
            }
        </script>
    </body>
</html>

Suppose I have an already registered user. When I load the page in the console, I received null. Although I expect the current user object to exist.

If I run the same code in the browser console

var user = firebase.auth().currentUser;
if (user) {
    console.log(user);
} else {
    console.log(user);
}

I can get the current user object.

I think it firebase.initializeApp(config);has some asynchronous behavior. What is the right way to get around this? Should I use a promise or something in a function firebase.initializeApp(config);? Kind of callback.

+4
source share
2 answers

. . auth - : https://firebase.google.com/docs/auth/web/manage-users

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in and currentUser will no longer return null.
  } else {
    // No user is signed in.
  }
});
+8

:

function canActivate(){
    return new Promise(resolve => {
        if (firebase.auth().currentUser) {
            resolve(true);
        } else {
            const unsubscribe = firebase.auth().onAuthStateChanged(function (user) {
                unsubscribe();
                if (user) {
                    resolve(true);
                } else {
                    resolve(false);
                }
            });
        }
    });
}

SPA, , firebase.auth().currentUser == true. , firebase.auth().currentUser == false. firebase.initializeApp(config); , firebase.auth().onAuthStateChanged, init.

0

All Articles