Quantcast
Channel: Ionic Framework - Ionic Forum
Viewing all articles
Browse latest Browse all 48980

Issue with Ionic Storage - Recreates the storage over and over

$
0
0

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.

2 posts - 2 participants

Read full topic


Viewing all articles
Browse latest Browse all 48980

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>