Root state of provider


#1

Hi,
I have this auth service with user property which is set when logged.
but then I route to different page, the user property is null.
I know when I was testing angualr2 I used to import auth service in app.ts and bootstrap it.
but I don’t see that option in Ionic2.
I did looked up ionicBootstrap its blank I guess still under development.


#2

I’m not 100% sure of your setup, but something that I have been doing is writing a user object to local storage http://ionicframework.com/docs/v2/api/platform/storage/LocalStorage/

e.g.

Login Screen

// Success response from server with user object:
this.dataservice.signIn(this.authForm.value.email, this.authForm.value.password).then(result => {
  if (result.success) {
    loading.dismiss();
    this.setUser(result.user);
  }
}); // removed error handling to save space


setUser(user) {
    this.userController.setUserLoggedIn(user);
}

UserController

import {Injectable} from '@angular/core';

@Injectable()
export class UserController {

    static get parameters() {
        return [];
    }

    constructor() {
        this.DATA_KEY = "user";
        this.dataService = dataService;
    }

    setValueForKey(value, key) {
        return this.getObjects().then(object => {
            if (object) {
                object[key] = value;
                return this.saveToLocalStorage(object);
            } else {
                let newObject = {};
                newObject[key] = value;
                return this.saveToLocalStorage(newObject);
            }
        })
    }

    getObjects() {
        //Gets objects from localStorage based on key
        return this.localData.loadData(this.DATA_KEY).then(objects => {
            if (objects) {
                return objects;
            } else {
                return null;
            }
        });
    }

    formatUser(user) {
      //Saving user info that is specific to my app
        return {
            email: user.email,
            uid: user.uid,
            u: user.u,
            refreshToken: user.refreshToken
        }
    }

    userLoggedIn() {
        return this.getObjects().then(objects => {
            if (objects) {
                return objects.user ? true : false;
            } else {
                return false;
            }
        });
    }
}

This will allow you to persist the object in memory. You can also store in SQLStorage for extra reliability, which I would also recommend.