Javascript 无法读取未定义的属性“ready”;区域:;任务:承诺;值:TypeError:无法读取未定义的属性“ready”
我正在尝试访问firebase onAuthStateChanged函数中的本地存储值。根据这一点,我想重定向用户。但我得到了这个错误。当我检查firebase onAuthStateChanged函数外部的存储值时,它工作正常。有人能告诉我为什么我无法访问onAuthStateChanged函数中的离子存储值吗 先谢谢你 home.page.tsJavascript 无法读取未定义的属性“ready”;区域:;任务:承诺;值:TypeError:无法读取未定义的属性“ready”,javascript,firebase,firebase-authentication,ionic4,Javascript,Firebase,Firebase Authentication,Ionic4,我正在尝试访问firebase onAuthStateChanged函数中的本地存储值。根据这一点,我想重定向用户。但我得到了这个错误。当我检查firebase onAuthStateChanged函数外部的存储值时,它工作正常。有人能告诉我为什么我无法访问onAuthStateChanged函数中的离子存储值吗 先谢谢你 home.page.ts constructor(public storageService : StorageService){} ngOnInit() {
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
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)
}
}
在代码中,您有以下内容:
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.
}
});
您应该将其更改为:
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.
}
});
使用arrow函数,该函数使用词法范围,这意味着您将能够读取在此函数之外定义的变量