angular - 登录后未定义Angular 7令牌
问题描述
尝试获取 Token 值并保持用户登录,直到用户单击注销。如果我尝试将它保存在变量中,它会显示未定义,我可以在其中看到令牌值console.log()
**Auth.service.ts
signIn(email: string, password: string) {
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then(response =>
firebase.auth().onAuthStateChanged(
(user) => {
if(user){
user.getIdToken().then(
data => this.token = data
)
}
}
)
)
.then(
response => {
this.router.navigate(['dashboard']);
}
)
.catch(error => console.log(error));
}
getToken() {
firebase.auth().onAuthStateChanged(function(user){
if(user){
user.getIdToken().then(
function(data){
// console.log(data);
})
}
});
}
框架:Angular7
解决方案
如果你想打电话then
,你需要返回一个Promise。像这样
getToken() {
return new Promise((resolve, reject) => {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
user.getIdToken().then(function(data) {
resolve(data);
}).catch(reject);
} else {
reject('Error while executing onAuthStateChanged');
}
});
});
}
推荐阅读
- python - Python从文件属性中的自定义选项卡获取数据
- python - 如何从 Instagram 故事洞察图 API 中获取向上滑动计数?
- android - 如何在 android 中从 NIST P-256 字符串私钥生成 PrivateKey
- python - Python为python项目生成exe
- r - R - 转置后如何创建“空”数据框?
- clickhouse - 如何正确编写clickhouse SQL?
- solidity - BEP20 代币不会被交换为 BNB 并发送到慈善钱包
- google-tag-manager - How did Google Ads find out my campaign's conversion even if customer visited different HTML page before firing final tracking code?
- javascript - 如何在 jQuery 中从外部 API 输出 JSON 数据,就像我在控制台日志中看到的那样,在 HTML 中(在 jQuery 中格式化 JSON)
- python - Python 将数据写入 csv 时的错误预测