AngularFire 2访问.subscribe()之外的数据

时间:2017-10-23 08:19:16

标签: angular firebase angularfire2

我使用此代码从数据库中提取用户数据。

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {AngularFireAuth} from 'angularfire2/auth';
import {AngularFireDatabase,AngularFireList} from 'angularfire2/database';

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

export class ProfilePage {
  profileData: Observable<any[]>

  constructor(private fire:AngularFireAuth,private db :AngularFireDatabase,public navCtrl: NavController) {

    this.profileData = this.fire.authState.switchMap(auth => this.db.object(`profile/${auth.uid}`).snapshotChanges().map(action => {
      const $key = action.payload.key;
      const data = { $key, ...action.payload.val() };
      return data;
    }))
    .subscribe(profile =>{
      this.profileData = profile;
      console.log(this.profileData.username); // this is working.
    });
    console.log(this.profileData.username); // this is undefined
    // How to access username outside subscribe function ?
  }
}

我的问题是:如何在订阅功能之外访问用户名以在其他地方使用它?我在代码上添加了评论。

2 个答案:

答案 0 :(得分:0)

未定义,因为profileData需要一些时间来获取其值,并且在数据到达时调用subscribe()方法。 但订阅回调之外的console.log()正在直接执行。

但如果需要,您可以在模板中使用profileData。它将在数据到达并且subscribe()函数已执行时更新。

答案 1 :(得分:-1)

像这样导入,

import { AngularFireDatabase, FirebaseObjectObservable } from 'angularfire2/database';

在类声明变量中,如

profileData: FirebaseObjectObservable<any[]>;
相关问题