Home > Software design >  How to get Capacitor Storage values before doing http call IONIC 6
How to get Capacitor Storage values before doing http call IONIC 6

Time:03-18

I've been looking for a tutorial on how to get some values I have on my Capacitor Storage in Ionic 6 and use them before doing the HTTP request.

Example method in cart.service.ts:

getCart() {
  Storage.get({ key: 'token' }).then( response => {
  this.token = JSON.parse(response.value);
});
return this.http.get<Product[]>(this.token.api_route   'user/cart');
}

What I want to call on onInit:

this.cartService.getCart().subscribe(response => {
  this.products = response;
});

So the main problem is that token is null because getting it from storage is async. How can I solve that problem? And get the token.api_route before doing HTTP call?

CodePudding user response:

Use a promise instead of an observable. You could use http.get(url).toPromise() to achieve that.

Here is an example:

import { Component } from '@angular/core';
import { Storage } from '@capacitor/storage';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  html = 'hello';
  constructor(public http: HttpClient) {}

  async test() {
    await this.saveToStorage();
    this.problem();
  }

  async saveToStorage() {
    console.log('Saving something to local storage...');
    await Storage.set({
      key: 'url',
      value: 'https://jsonplaceholder.typicode.com/posts',
    });
  }

  problem() {
    this.getApiValue().then((value) => {
      this.html = JSON.stringify(value) ;
    });
  }
  async getApiValue() {
    const urltogo = await Storage.get({key:'url'});
    return this.http.get(urltogo.value).toPromise();
  }
}
  • Related