Issue with Ionic Storage - Recreates the storage over and over

I would like to achieve something easy, but it won’t work.

Once a user logs on I would like to save the token to the local storage and once the user comes back, it should check, if the token is already set up and forward directly to a secure page instead of showing the login again.

I adopted this authentication service:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map, tap, switchMap } from 'rxjs/operators';
import { BehaviorSubject, from, Observable, Subject } from 'rxjs';
import { Router } from '@angular/router';

import { Storage } from '@ionic/storage-angular';

const TOKEN_KEY = 'EPTOKEN';


@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {
  private _storage: Storage | null = null;
  showMenu: boolean = false;
  isAuthenticated: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(null);
  token = '';  

  constructor(
    public router: Router,
    private http: HttpClient,
    private storage: Storage
  ) {
    this.init(),
    this.loadToken();
  }

  async init() {
    const storage = await this.storage.create();
    this._storage = storage;  
  }
  
  login(credentials: {email, password}): Observable<any> {
    return this.http.post(`https://xxxxxx`, credentials).pipe(
      map((data: any) => data.token),
      switchMap(token => {
        return from(this._storage?.set(TOKEN_KEY, token));
      }),
      tap(_ => {
        this.showMenu = true;
        this.isAuthenticated.next(true);
      })
    );
  }
  
  logout(): Promise<void> {
    console.log('Reached final logout.');
    this.showMenu = false;
    this.isAuthenticated.next(false);
    return this._storage?.remove(TOKEN_KEY);
  }

  async loadToken() {
    const token = await this._storage?.get(TOKEN_KEY);    
    if (token && token.value) {
      console.log('set token: ', token.value);
      this.token = token.value;
      this.showMenu = true;
      this.isAuthenticated.next(true);
    } else {
      this.showMenu = false;
      this.isAuthenticated.next(false);
    }
  }
}

But the storage is recreated over an over on “init()”, but if I don’t call storage.create() I have errors in the console.

If you remove initialization code from the constructor of your service and place it somewhere like app.component OnInit, your problem will go away.

The reason for multiple calls to init is probably due to multiple initialization of the service. You might have this service in the providers array of one or more module or component declarations. For each one of this declarations a new instance of your service gets created.