首页 > 解决方案 > 将 Firebase 数据设置为 html 文件中的属性

问题描述

好的,所以我在 ionic 还很新,我遇到了这个问题,我从 firebase 获取用户数据,但是每当我将它设置为公共变量并尝试在 html 文件中引用它时,我都会收到一个日志错误“不能将‘变量名’设置为未定义的属性”。这是我的代码,可以更清楚地解释和理解我想要实现的目标。谢谢你。

.ts 文件:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams,AlertController, 
LoadingController, Loading } from 'ionic-angular';
import {AngularFireAuth} from 'angularfire2/auth';
import { MenuPage } from '../menu/menu';
import firebase from 'firebase';
import { first } from 'rxjs/operators';



@IonicPage()
@Component({
  selector: 'page-account',
  templateUrl: 'account.html',
})
export class AccountPage {

   public userinfo;

  constructor(public navCtrl: NavController, public navParams: NavParams,
    private alertCtrl:AlertController, public fAuth:AngularFireAuth,
    public loading:LoadingController) {  
  }
  ionViewDidLoad() {
    console.log('ionViewDidLoad AccountPage');
    this.readData();
  }

  isLoggedIn(){
    return this.fAuth.authState.pipe(first()).toPromise();
  }

   userStatus(){
    const user =  this.isLoggedIn()
    if(user){
      console.log('logged in');
      this.readData();
    }else{   
   }
 }


   async readData(){
      let load = this.loading.create({
        content: "Setting up your profile...",
        spinner:'dots'
      });
      load.present();
      await this.fAuth.authState.subscribe((user:firebase.User) =>{
        if(user){
          firebase.database().ref('/users/' + 
user.uid).once('value').then(function(snapshot){   
            if(snapshot.exists()){
              var data = (snapshot.val() && snapshot.val().username) || 
'Anonymous';
              //this.userinfo = data;
              console.log(data);
            }else{
              console.log("i need a name");                             
            }});       
        }else{
          console.log("not logged in, log in please");  
          this.alertLogin();       
        };
      });
      console.log(this.userinfo );
      load.dismiss();
  }


  getName(){
    let alert = this.alertCtrl.create({
      title: 'Hello new friend! :) please can you tell us your name...',
      inputs: [
        {
          name: 'name',
          placeholder: 'name'
        }
      ],
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          handler: data => {
            console.log('Cancel clicked');
            this.navCtrl.setRoot(MenuPage);
          }
        },
        {
          text: 'Confirm',
          handler: data => {
                 this.fAuth.authState.subscribe((user:firebase.User) =>{
                  firebase.database().ref('/users/' + user.uid).set({
                    username:data.name 
                  });
                 });                 
           }
        }
      ]
    });
    alert.present(); 
  }

  alertLogin(){
    //if user is not already logged in
    let alert = this.alertCtrl.create({
    title: 'Whoa there Sally! you need to log in first! :)',
    inputs: [
      {
        name: 'email',
        placeholder: 'email'
      },
      {
        name: 'password',
        placeholder: 'Password',
        type: 'password'
      }
    ],
    buttons: [
      {
        text: 'Cancel',
        role: 'cancel',
        handler: data => {
          console.log('Cancel clicked');
          this.navCtrl.setRoot(MenuPage);
        }
      },
      {
        text: 'Login',
        handler: data => {
          this.login(data.email,data.password);
        }
      },{
        text: 'Register',
        handler: data => {
          this.register(data.email,data.password);
        }
      }
    ]
  });
   alert.present();
  }

  async login(email,password){
    try{
      var login = await this.fAuth.auth.signInWithEmailAndPassword(
        email,
        password
      );
      if(login){
        console.log("Successfully logged in!");        
      }
    }catch(err){
      console.error(err);
      alert("Sorry we couldnt find you in our system :(");
      this.navCtrl.setRoot(MenuPage);
    }
  }

async register(email,password){
    try{
      var reg = await this.fAuth.auth.createUserWithEmailAndPassword(
        email,
        password
      );
       if(reg){
         this.getName();
         console.log("successfully registered!");
         this.navCtrl.setRoot(AccountPage);
      }
    }catch(err){
      console.error(err);
    }
  }

  logout(){
    this.fAuth.auth.signOut();
  }

}

.html 文件:

<ion-item>
    <h1>{{userinfo}}</h1>
 </ion-item>

标签: firebaseionic3

解决方案


好的,所以我基本上已经尝试了所有方法,并决定将名称上传到数据库并将其本地写入应用程序的存储中。我将在稍后的申请过程中提取名称以及更多详细信息。但是,如果有人找到这篇文章的答案,我将不胜感激!


推荐阅读