Search code examples
javascriptangularionic-frameworkionic4

Zone Aware Promise with Ionic 5 and Angular 10


I'm new to Promises (usually use Observables) and Ionic.

I have using capacitor, I have stored the user Id in local storage with this:

import { Plugins } from '@capacitor/core';

async storeAuthData(token: string, user: IUserAuth): Promise<void>{

    await Plugins.Storage.set({
        key: '_token',
        value: token
    });

    await Plugins.Storage.set({
        key: '_u',
        value: JSON.stringify(user)
    });
}

I want to retrieve the userId from that storage set. I have wrapped my Promise in a return and believe I've done the correct syntax, but when I call this function I get the Zone Aware Promise _state: null info in the console.

 async getUserId(): Promise<string> {
    return Plugins.Storage
            .get({key: '_u'})
            .then(userObj => {
                var user = JSON.parse(userObj.value);
                return user.id.toString();
            }).catch(err => {
                console.log(err)
                return null;
            });
}

Any ideas on how to do this?

calling the getUserId func like this:

var id = await this.auth.getUserId();
console.log(id)

Solution

  • One thing about promises is that we have to wrap them in async methods.

    So your code would be something like this:

    async storeAuthData(token: string, user: IUserAuth): Promise<void> {
      // now we introduce the await or the code will run out of control
      await Plugins.Storage.set({
        key: '_u',
        value: JSON.stringify(user)
      });
    
      // same here
      await Plugins.Storage.set({
        key: '_token',
        value: token
      });
    }
    

    Then retrieving it

    async getUserId(): Promise <string> {
      return Plugins.Storage
        .get({
          key: '_u'
        })
        .then(userObj => JSON.parse(userObj.value))
        .catch(err => {
          console.log(err)
          return null;
        });
    }
    

    And when we are calling we have to use the await keyword too.

    Something like this:

    console.log('userId', await UserService.getUserId())