我有一个 ionic 2 应用程序,正在使用 native FB 登录来检索名称/图片并将其保存到 NativeStorage。流程是我打开WelcomePage,登录并保存数据。从那里,navPush 到主页。到目前为止,它工作得很好。

但是,我有一个 ProfilePage(可通过 tabRoot 访问),但失败了。原因是在我的 profile.html 我有以下标签应该呈现用户名(这适用于主页,但不适用于 ProfilePage):

{{ user.name }}

我在 XCode 上得到的错误是:

2017-05-02 18:40:41.657374 FoxBox App[1102:226159] 错误:导航失败:未定义不是对象(评估“co.user.picture”)

请注意,出于某种原因,它以“co”开头。我不知道它来自哪里或它意味着什么。

这是欢迎页面代码:
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's 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);
    });

  }
}

这是主页代码:
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!")
      })

  }

}

这是失败的 ProfilePage 代码:
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);
    });
  }
}

这是 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>

我应该提到的是,如果我从 ProfilePage.html 中删除 {{ user.name }} 和 {{ user.picture }},似乎没有任何问题。事实上,如果您在 ProfilePage 的 ts 中注意到,我可以在 Alert 和 Console.log 用户名 (data.name) 中没有任何问题。

我是初学者,希望在这方面提供任何简洁的帮助。谢谢你。

最佳答案

我终于找到了解决方案。在 html 文件 (ProfilePage.html) 中,我使用了 *ngIf 条件:

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

这将引入延迟,使得“用户”对象在从 NativeStorage 读取时不再为空。

或者,Elvis Operator 也适用于我:
<div> {{ user?.name }} </div>

关于Ionic2 NativeStorage 无法获取项目(用户),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43749846/

10-11 23:43