1

I am not sure what the problem is here but i can't return a value. I do not want to use sqlite right now.

 doLogin(event){
    this.storage.get('user').then((val) => {
      this.username=val;
      console.log(this.username);
      console.log(val);
  });

}

The problem is the 1st log returns undefined but the second log is returning the correct values.

Edit : Really sorry guys. Both the logs are working fine. But the log mentioned below is not working. This is causing the if statement to return false even though all the values match Full code for the file

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { FormBuilder, Validators } from '@angular/forms';
import { Storage } from '@ionic/storage';

@Component({
  selector: 'login',
  templateUrl: 'login.html'
})
export class LoginPage {

   username: string;
   password: string;

  public loginForm = this.fb.group({
    password: ["", Validators.required],
    user: ["", Validators.required],

  });

  constructor(public navCtrl: NavController, public fb:FormBuilder, public storage:Storage) {

  }


  doLogin(event){
    this.storage.get('user').then((val) => {
      this.username=val;
      console.log( this.username);
      console.log(val);
  });

  this.storage.get('password').then((val) => {
       this.password=val;
  });
  console.log(this.username); //NOT WORKING
      if( this.username == this.loginForm.get('user').value &&  this.password == this.loginForm.get('password').value)
          {
            console.log("Login Successful");
          }


  }
eko
  • 39,722
  • 10
  • 72
  • 98

2 Answers2

2

Promises are asynchronous..that console log statement is likely called before the db returns val. You can do this operation within then

If you are using promises, you can use Promise.all

let userCredentials = [this.storage.get('user'),this.storage.get('password')];
Promise.all(userCredentials).then(values =>{
  this.username = values[0];
  this.password = values[1];
   if( this.username == this.loginForm.get('user').value &&  this.password == this.loginForm.get('password').value)
      {
        console.log("Login Successful");
      }
});

Promise.all will call the array of promises and wait till all return.

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
0

We can use Observable from RxJs to check 2 promises from storage finish.

Observable.forkJoin([
   Observable.fromPromise(this.storage.get('user')), 
   Observable.fromPromise(this.storage.get('password'))
])
.subscribe(data=> {
    this.username = data[0];
    this.password = data[1];
    if (this.username == this.loginForm.get('user').value &&  this.password ==this.loginForm.get('password').value){
        console.log("Login Successful");
    }
});
Thien Hoang
  • 625
  • 3
  • 12