Search code examples
javascriptfirebasefirebase-authenticationionic4

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. 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. Can anyone tell me why I unable to access ionic storage values inside onAuthStateChanged() function?

Thank you in advance

home.page.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

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)
      }
    }

Solution

  • 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.