Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JWT in IONIC with Angular

when i nagivate to another page in my IONIC app the api call (GET) dont work as intended, they need a token for authorization but on the first time i navigate to that page, the storage.get doesnt get the token in time. If then i go back to the homepage and return back again it works as intended.

  ngOnInit(){
   this.storage.get('token')
    .then (result => this.token = result)
  }

  ionViewWillEnter(){
    this.loadData()
  }

  async loadData(){
    await this.getNotifications();
  }

using console logs i see that the first time i navigate to the page the token is empty. Seems like the storage.get takes too much time and the api call is executed before i get the token.
I tried with setting ngOnInit with async await it didnt work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It seems like you’re facing an issue with the timing of fetching the token from storage before making an API call. Since the storage.get method is asynchronous, there’s a chance that the API call is being executed before the token is retrieved. Here’s a possible solution to ensure that the token is fetched before making the API call:

ngOnInit() {
  this.fetchTokenAndLoadData();
}

async fetchTokenAndLoadData() {
  try {
    this.token = await this.storage.get('token');
    if (this.token) {
      await this.loadData();
    } else {
      console.log('Token not found');
    }
  } catch (error) {
    console.error('Error fetching token:', error);
  }
}

async loadData() {
  try {
    await this.getNotifications();
  } catch (error) {
    console.error('Error loading data:', error);
  }
}

By using the async/await syntax, you’re ensuring that the token is fetched before attempting to load the data. If the token retrieval fails for any reason, you can handle the error appropriately. This way, you won’t make the API call until you have a valid token.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading