[英]Cannot read property 'ready' of undefined ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Cannot read property 'ready' of undefined
I am trying to access local storage values inside firebase onAuthStateChanged() function.我正在尝试访问 firebase onAuthStateChanged() 函数中的本地存储值。 Depending on that I want to redirect users.
根据我想重定向用户。 But I am getting this error.
但我收到此错误。 When I check storage values outside the firebase onAuthStateChanged() function it works fine.
当我检查 firebase onAuthStateChanged() 函数之外的存储值时,它工作正常。 Can anyone tell me why I unable to access ionic storage values inside onAuthStateChanged() function?
谁能告诉我为什么我无法访问 onAuthStateChanged() 函数中的离子存储值?
Thank you in advance先感谢您
home.page.ts主页.ts
constructor(public storageService : StorageService){}
ngOnInit() {
this.validate()
}
async validate(){
this.afauth.auth.onAuthStateChanged( async function(user) {
if (user) {
// User is signed in.
await this.storageService.ready()
const name = await this.storageService.get('name')
const business_name = await this.storageService.get('business_name')
} else {
// No user is signed in.
}
});
}
storageservice.ts存储服务.ts
constructor( private storage: Storage) {
}
async get(key: string): Promise<any> {
try {
const result = await this.storage.get(key);
console.log('storageGET: ' + key + ': ' + result);
if (result != null) {
return result;
}
return null;
} catch (reason) {
console.log(reason);
return null;
}
}
async ready() : Promise<any>{
try {
this.storage.ready();
return true;
}
catch(err) {
console.log(err)
}
}
In your code, you have the following:在您的代码中,您有以下内容:
this.afauth.auth.onAuthStateChanged( async function(user) {
if (user) {
// User is signed in.
await this.storageService.ready()
const name = await this.storageService.get('name')
const business_name = await this.storageService.get('business_name')
} else {
// No user is signed in.
}
});
You should change it to this:你应该把它改成这样:
this.afauth.auth.onAuthStateChanged( async ((user) => {
if (user) {
// User is signed in.
await this.storageService.ready()
const name = await this.storageService.get('name')
const business_name = await this.storageService.get('business_name')
} else {
// No user is signed in.
}
});
Use arrow function which uses a lexical scope, which means you will be able to read the variable defined outside of this function.使用使用词法作用域的箭头函数,这意味着您将能够读取在此函数之外定义的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.