Ionic 2 basic: get user from storage and check username / password

1.1k views Asked by At

For a mobile app I use the ionic2 platform. The first screen is to log in, but I would remember the user information. Therefor I have created a Service (see below) The problem is that I have this error: Property 'email' does not exist on type '{}'.

The check for login is this one:

var  dataUser = this.userService.getUser().then(dataUser => {
      console.log(JSON.stringify(dataUser));
        this.userService.checkUser(dataUser.email,dataUser.password).then(dataCheck => {
    if (dataCheck)  {
        this.userService.setUser(dataCheck);
        this.nav.setRoot(HomePage);
    } else {
        console.log("not correct");
    }
});

});

So it is on getting dataUser.email that he throws this error... But I can't find any solution to fix this unfortunatly :(

import { Storage } from '@ionic/storage';
import {UserModel} from '../models/user.model'

@Injectable()
export class UserService {
   constructor(public http: Http, public storage: Storage) {
}

setUser(user) {
   this.storage.set('user',user);
}

getUser() {
   return new Promise(resolve => {
      this.storage.get('user').then((user) => {
        if (user != null) {
            resolve(user);
        } else {
            resolve(new UserModel()); 
        }
      });
    })
}

checkUser(email,password) {

}
1

There are 1 answers

1
ACES On BEST ANSWER

I use NativeStorage for this:

NativeStorage.setItem('user',{email: this.email, password: this.password}).then(() => {
    console.log("credentials stored");
}

and then get info

NativeStorage.getItem('user').then((user) => {
    console.log("this is email: " + user.email);
    console.log("this is password: " + user.pasword);
}

Don't forget to install plugin and import it

import { NativeStorage } from 'ionic-native';

Also read plugin documentation how to clear from Native Storage. I hope this helps.