无法从 firebase.auth().signInWithPopup(provider) 函数中更改变量

Can't change variable from within firebase.auth().signInWithPopup(provider) function

本文关键字:函数 改变 变量 provider signInWithPopup firebase auth      更新时间:2023-09-26

所以我定义了一个名为testVariable的变量,并在$scope.signIn()函数中将其设置为初始。然后在firebase.auth().signInWithPopup(provider).then()函数中,我将其更改为changed。当我在firebase.auth().signInWithPopup(provider).then()函数之外控制台.log()时,它返回initial。我希望它返回更改,下面的代码有什么问题?任何帮助将不胜感激。

var app = angular.module("myApp", []);
app.controller("MainController", ["$scope", function ($scope){
    $scope.googleSignInStyle = {};
    $scope.googleSignInText = "";
    $scope.signIn = function (){
        var provider = new firebase.auth.GoogleAuthProvider();
        var testVariable = "initial";
        firebase.auth().signInWithPopup(provider).then(function(result) {
            var token = result.credential.accessToken;
            var user = result.user;
            var providerData = user.providerData[0];
            firebase.database().ref('users/' + providerData.displayName).set({Email: providerData.email, PhotoURL: providerData.photoURL, uid: providerData.uid});
            testVariable = "changed";
        }).catch(function(error) {
            var errorCode = error.code;
            var errorMessage = error.message;
            var email = error.email;
            var credential = error.credential;
            console.log ("Error! Error code: " + errorCode + ", Email: " + email + ", Credential: " + credential + ". That's all we know.");
        });
        console.log (testVariable);
    }
}]);

你对 .then() 的调用是异步运行的。这意味着它将在一段时间后返回firebase.auth().signInWithPopup(provider)时运行。

因此,您正在有效地更改testVariable的值,但是在打印出来之后。换句话说,.then() 内部发生的事情发生在你调用 console.log(testVariable) 之后。

如果您不熟悉承诺的概念,请阅读此内容。

问题是您尝试在signInWithPopup回调之外记录它。您的testVariable不会有任何值,因为signInWithPopup是异步的,并且在您调用console.log时它不会完成处理。

$scope.signIn = function (){
    var provider = new firebase.auth.GoogleAuthProvider();
    var testVariable = "initial";
    firebase.auth().signInWithPopup(provider).then(function(result) {
        var token = result.credential.accessToken;
        var user = result.user;
        var providerData = user.providerData[0];
        firebase.database().ref('users/' + providerData.displayName).set({Email: providerData.email, PhotoURL: providerData.photoURL, uid: providerData.uid});
        testVariable = "changed";
        console.log (testVariable);
    }).catch(function(error) {
        var errorCode = error.code;
        var errorMessage = error.message;
        var email = error.email;
        var credential = error.credential;
        console.log ("Error! Error code: " + errorCode + ", Email: " + email + ", Credential: " + credential + ". That's all we know.");
        console.log (testVariable);
    });
}

解决它将取决于您要实现的行为。上面的代码是一种可能的解决方案,请注意,我刚刚在回调中插入了console.log调用。