Ionic2 NativeStorage cannot getItem (user)

I have an ionic 2 app and I am using my own FB Login to get the name / pic and store it in NativeStorage. The flow is that I open the WelcomePage, register and save the data. From there, navPush to HomePage. So far this works great.

However, I have ProfilePage (accessible via tabRoot) crashing. The reason is that in my profile.html I have the following tag that should display Username (this works on HomePage but not ProfilePage):

{{ user.name }}

      

The error I am getting on XCode:

2017-05-02 18: 40: 41.657374 FoxBox Application [1102: 226159] ERROR: Failed to navigate: undefined is not an object (estimate "co.user.picture")

Note that for some reason he adds it with "co." which I have no idea where it comes from or what it means.

Here is the WelcomePage code:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import { HomePage } from '../home/home';
import { AboutPage } from '../about/about';


import { Facebook, NativeStorage } from 'ionic-native';
//import { FacebookAuth, User, Auth } from '@ionic/cloud-angular';
import { CloudSettings, CloudModule } from '@ionic/cloud-angular';

import {GoogleAnalytics} from 'ionic-native';

@Component({
  selector: 'page-welcome',
  templateUrl: 'welcome.html'
})
export class WelcomePage {

  FB_APP_ID: number = 1234567890;

  homePage = HomePage;
  aboutPage = AboutPage;

  constructor(
    public navCtrl: NavController,
    //public facebookAuth: FacebookAuth, 
    //public auth: Auth,
    //public user: User,
    ) {

    Facebook.browserInit(this.FB_APP_ID, "v2.8");

  }


doFbLogin(){
    //alert("fb is logged in");
    let permissions = new Array();
    let nav = this.navCtrl;
    //the permissions your facebook app needs from the user
    permissions = ["public_profile"];


    Facebook.login(permissions)
    .then(function(response){
      let userId = response.authResponse.userID;
      let params = new Array();

      //Getting name and gender properties
      Facebook.api("/me?fields=name,gender", params)
      .then(function(user) {
        user.picture = "https://graph.facebook.com/" + userId + "/picture?type=large";
        //now we have the users info, let save it in the NativeStorage
        NativeStorage.setItem('user',
        {
          name: user.name,
          gender: user.gender,
          picture: user.picture,
          email: user.email,
        })
        .then(function(){
          nav.push(HomePage);
          console.log("User Data Stored");
        }, function (error) {
          console.log(error);
        })
      })
    }, function(error){
      console.log(error);
    });

  }
}

      

Here is the HomePage code:

import { Component } from '@angular/core';
import { NavController, Platform } from 'ionic-angular';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

import { ClaimPage } from '../claim/claim';


import { SocialSharing } from '@ionic-native/social-sharing';

import { Facebook, NativeStorage } from 'ionic-native';
//import { FacebookAuth, User, Auth } from '@ionic/cloud-angular';
import { CloudSettings, CloudModule } from '@ionic/cloud-angular';

import {GoogleAnalytics} from 'ionic-native';



@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  posts: any;
  sendme: any;
  claimPage = ClaimPage;
  user: any;
  userReady: boolean = false;

  constructor(
    public navCtrl: NavController, 
    public http: Http,
    private sharingVar: SocialSharing,
    public platform: Platform,
    ) {


    // Check to see if user already exists (via FB login)
    let env = this;
    NativeStorage.getItem('user')
    .then(function (data){
      env.user = {
        name: data.name,
        gender: data.gender,
        picture: data.picture
      };
        env.userReady = true;
        // console.log(data.name);
    }, function(error){
      console.log(error);
    });


    this.platform.ready().then(() => {
      //alert("platform is ready");
      GoogleAnalytics.trackView("Home-Page", "http://foxboxapp.com/home", true);
      //alert("GA called");
    });

    this.http.get('http://getyourtryston.com/foox/sample.php').map(res => res.json()).subscribe(data => {
        this.posts = data.data.children;

    });

  }



  otherShare(){
    this.sharingVar.share("FoxBox App","Get Awesome College Deals",null/*File*/,"http://fooxsocial.com")
    .then(()=>{
        //alert("Success");
      },
      ()=>{
         alert("Sharing Failed!")
      })

  }

}

      

And here's the profile code that doesn't work:

import { Component } from '@angular/core';
import { NavController, Platform } from 'ionic-angular';

import { WelcomePage } from '../welcome/welcome';



import {GoogleAnalytics} from 'ionic-native';
import { SocialSharing } from '@ionic-native/social-sharing';
import { Facebook, NativeStorage } from 'ionic-native';
//import { FacebookAuth, User, Auth } from '@ionic/cloud-angular';
//import { CloudSettings, CloudModule } from '@ionic/cloud-angular';

@Component({
  selector: 'page-about',
  templateUrl: 'about.html'
})

export class AboutPage {

  user: any;
  userReady: boolean = false;

  constructor(
    public navCtrl: NavController,
    public platform: Platform,
    private sharingVar: SocialSharing,
    //public facebookAuth:FacebookAuth, 
    //public auth:Auth,    
    ) {



    // Check to see if user already exists (via FB login)
    let env = this;
    NativeStorage.getItem('user')
    .then(function (data){
      env.user = {
        name: data.name,
        gender: data.gender,
        picture: data.picture
      };
        env.userReady = true;
        // console.log(data.name);
    }, function(error){
      console.log(error);
    });



    // PLATFORM READY, do your thang!
    this.platform.ready().then(() => {

      // Ping Google Analytics
      GoogleAnalytics.trackView("Profile Page", "http://foxboxapp.com/home", true);


    });


  }

  otherShare(){
    this.sharingVar.share("FOOX Social App","Get Awesome College Deals",null/*File*/,"http://fooxsocial.com")
    .then(()=>{
        //alert("Success");
      },
      ()=>{
         alert("Sharing Failed!")
      })

  }


  doFbLogout(){
    var nav = this.navCtrl;
    Facebook.logout()
    .then(function(response) {
      //user logged out so we will remove him from the NativeStorage
      NativeStorage.remove('user');
      nav.push(WelcomePage);
    }, function(error){
      console.log(error);
    });
  }
}

      

And here is ProfilePage.html

<ion-header>

  <ion-navbar color="light" hideBackButton="true">

      <ion-buttons end>
      <button ion-button icon-only (click)="otherShare()">
        <ion-icon name="share"></ion-icon>
      </button>
    </ion-buttons>

  </ion-navbar>

</ion-header>

<ion-content>

<ion-card class="pCard">
  <div class="pHeader" align="center">
    <div *ngIf="user" class="pImgBox" align="center">
      <img class="pImage" src="{{ user.picture }}">
    </div>
    <div class="pUsername" align="center">
      <div *ngIf="user"> {{user.name}} </div>
      <br>
      <span class="pSchool">(Santa Monica College)</span>
    </div>
  </div>

  <ion-list>
    <ion-item class="pItems">
      Share App
    </ion-item>
    <ion-item class="pItems">
      Give Us Feedback
    </ion-item>
    <ion-item class="pItems">
      Suggest Vendors
    </ion-item>
    <ion-item class="pItems">
      Privacy & Terms of Service
    </ion-item>
    <ion-item class="pItems">
      Log Out
    </ion-item>
    <ion-item class="pItems">
      Delete Account
    </ion-item>
  </ion-list>
</ion-card>

<button ion-button round (click)="doFbLogout()">Log Out</button>

</ion-content>

      

I should mention that if I remove {{user.name}} and {{user.picture}} from my ProfilePage.html, there seems to be no problem. In fact, if you noticed in ts ProfilePage, I can both Alert and Console.log username (data.name) without any problem.

I am a beginner and would appreciate some brief help in this regard. Thank.

+3


source to share


1 answer


I finally found a solution. In the html file (ProfilePage.html) I used the * ngIf conditional:

<div *ngIf="user"> {{user.name}} </div>

      

This will cause a delay so that the "user" object is no longer null as it is reading from NativeStorage.



Alternatively, the Elvis operator works for me too:

<div> {{ user?.name }} </div>

      

+2


source







All Articles