Angular Storage get Return Undefined

Asked

Viewed 89 times

0

Developing an Ionic / Angular APP and I am using Storage to save and retrieve user token information. The problem is that I am having to call/instantiate N s times a function to retrieve the token and even then sometimes the token is not returned.

On the start screen I simulate a login with the data I need:

import { Storage } from '@ionic/storage';
    
private _Storage: Storage

this._Storage.set('X-Access-Token', 'f27bf5399b81c701bd9d6158ca67bb58');
this._Storage.set('isLogged', 'true');
this._Router.navigate(['/dashboard']);

To recover the X-Access-Token in the Dashboard compoment (and all other components) I have to call the Getaccesstoken function with ngOnInit, and then from within the main function of each component.

    XAccessToken: any;

    ngOnInit() { 
       this.GetXAccessToken();
    }
    
     GetXAccessToken() {
        this._Storage.get('X-Access-Token').then((token) => {
          this.XAccessToken = token;
        });
      }
    
    ionViewDidEnter() {
        this.GetChannelsFollowed();  
      }
    
      async GetChannelsFollowed() {
        this.GetXAccessToken();
     ....
     }

2 answers

0

What happens is that get Storage is an asynchronous request, so sometimes I don’t get the answer in time to continue the next functions, and it generates the error. To solve the problem I created a observable and request the token through this.

export interface ICredential {
    IsLogged?: boolean;
    XAccessToken?: string;
}

  Session(): Observable<ICredential> {
    return new Observable<ICredential>(observer => {
      observer.next(this._ICredential);
    });
  }

-1

When you use Storage.get, it already validates for you whether it exists or not, not needing to validate whether it is set or not. Try:

this.storage.get('X-Access-Token').then((token) => {
  return (token);
});
return('');

So you will always have a return inside the token, just compare it later

Browser other questions tagged

You are not signed in. Login or sign up in order to post.