[英]Firebase authentication onAuthStateChanged responding after function body
I am creating an application with firebase.我正在使用 Firebase 创建一个应用程序。 When loading any page, I am checking for authentication via following code.
加载任何页面时,我正在通过以下代码检查身份验证。 When I call isAuthenticated from landing page, its returning false even though user is already logged in and persistence is LOCAL( https://firebase.google.com/docs/auth/web/auth-state-persistence ), after false returned the inner function is executed.
当我从登陆页面调用 isAuthenticated 时,即使用户已经登录并且持久性是本地的( https://firebase.google.com/docs/auth/web/auth-state-persistence ),它也会返回 false,在 false 返回之后内部函数被执行。
authentication.ts
身份验证.ts
import {auth} from "../firebase";
export function isAuthenticated() {
console.log("Started!");
auth.onAuthStateChanged(function(user) : boolean {
console.log("Coming inside authentication");
if (user) {
console.log('User signed in - auth success! ', user.email);
return true;
} else {
console.log('User not signed in - auth failed! ');
return false;
}
});
console.log("Something wrong, coming here!");
return false;
};
I am getting false even before the inner onAuthStateChanged
function runs.甚至在内部
onAuthStateChanged
函数运行之前,我就变得错误了。 Please look at the screen shot.请看屏幕截图。
How to make sure I always get return value of inner function.如何确保我总是得到内部函数的返回值。
auth.onAuthStateChanged
doesn't return anything helpful. auth.onAuthStateChanged
不会返回任何有用的信息。 It adds a listener asynchronously that gets invoked whenever the user signs in or out.它会异步添加一个侦听器,每当用户登录或退出时都会调用该侦听器。 It's not very useful for knowing the user state immediately, and you can't simply return a value out of the callback for use in an enclosing function.
立即了解用户状态不是很有用,并且您不能简单地从回调中返回一个值以用于封闭函数。
If you want to know immediately if a user is currently signs in or out, you should just use auth.currentUser to get a User object.如果您想立即知道用户当前是登录还是退出,您应该只使用auth.currentUser来获取 User 对象。 It will be null if the user is signed out.
如果用户已注销,它将为空。 However, this status can change over time.
但是,这种状态会随着时间而改变。 If you're interested in changes over time, use the listener instead.
如果您对随时间的变化感兴趣,请改用侦听器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.