Read Local - Storage syncron/direct

I created an app that saves an api-key within the local storage. I’d like to include this api-key in the header of every request I send.
To do so, I wrote a service and I would like to synchronously load the api-key from the storage using a function.
this.headers = new Headers(); this.headers.append('X-Auth', this.localData.getApiKey());
The problem is that if I access the storage using ionic/angular, a „promise“ is returned.

What I need is a function that delivers a string i.e.:

Is it possible to use promise in way that makes my function deliver a string? I tried the following without success:
getApiKey(){ return"'apiKey'").then((key) => { return key; }); }

No, it’s not possible. That’s the entire point of asynchronous code. Probably the best way is to then chain off the promise you get and return the Observable you get from the http call.

I implemented something pretty much the same recently, I ended up putting this kinda stuff into an Authentication Service. Using async storage does add a little bit of overhead to down stream code but it’s far from anything that’s unmanageable - I’m sure when all you needed is to do'apiKey') it would be pretty straight forward, but if you needed some deterministic from multiple asynchronous this.storge.get, it’d be a good idea to encapsulate and hide away the plumbings of multiple promises. It’s not too messy for anyone willing to learn and use the Promise API:

–It is possible to same code snippet to show my your Authentication Service. The only idea is to return the promoise an every access to this storage item, i must write the then() funktion etc. this ist many duplicate code.–

My solution, is this so o.k?:

` getApiKey(){
.then(res => this.apiKey = res );

get(url) {
let headers = new Headers({
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json; charset=utf-8’

return Observable.fromPromise(this.localData.getApiKey())
    .flatMap((apiKey) => {
      headers.append('X-Auth', apiKey);

      return this.http.get(url, {
        headers: headers


fixed by using angular2 object instead of ionic 2 storage:

setApiKey(apiKey:string) { localStorage.setItem("apiKey", apiKey); } getApiKey(){ return localStorage.getItem('apiKey'); }

Hi Nachtigal,

I have the same problem. How you fixed you issue ?

I use import { Storage } from '@ionic/storage' for my localstorage


It is not a problem. You must adapt to asynchronous programming.

Hello rapropos,

i solved my issue. i used localStorage instead of ionic native storage.

Thank you.