Невозможно прочитать свойство 'ready' из undefined; Зона: <root>; Задача: Promise.then; Значение: TypeError: Невозможно прочитать свойство 'ready' из неопределенного - PullRequest
0 голосов
/ 13 января 2020

Я пытаюсь получить доступ к локальным значениям хранилища внутри функции firebase onAuthStateChanged (). В зависимости от этого я хочу перенаправить пользователей. Но я получаю эту ошибку. Когда я проверяю значения хранилища вне firebase, функция onAuthStateChanged () работает нормально. Может кто-нибудь сказать мне, почему я не могу получить доступ к значениям памяти ioni c внутри функции onAuthStateChanged ()?

Заранее спасибо

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

1 Ответ

1 голос
/ 13 января 2020

В вашем коде у вас есть следующее:

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

Использовать функцию стрелки, которая использует лексическую область, что означает, что вы будете быть в состоянии прочитать переменную, определенную вне этой функции.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...