UID没有显示构造函数

时间:2016-11-09 10:16:07

标签: authentication angular firebase angularfire

我在尝试将uid从构造函数中删除时遇到了一些问题。当我运行此代码时,uid在Test 1日志中完美显示。但是Test2日志显示未定义。当构造函数关闭时,uid是否会删除自己?

import { Component, OnInit } from '@angular/core';
import {AngularFire, FirebaseObjectObservable, FirebaseListObservable} from 'angularfire2';

@Component({
  selector: 'dashboard',
  templateUrl: 'dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent {
  userid:string;
  users:FirebaseListObservable<any[]>;
  constructor(public af: AngularFire) {
    this.af.auth.subscribe(auth => {
      console.log(auth.uid);
      this.userid = auth.uid;
      console.log("Test 1 "+ this.userid);
    });
    console.log("Test2 "+ this.userid);
  }
}

这是我在控制台中的输出

Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode.
dashboard.component.ts:18 Test2 undefined
dashboard.component.ts:14 CgTltJ1h2TUFS5teoACCxoPHP1g1
dashboard.component.ts:16 Test 1 CgTltJ1h2TUFS5teoACCxoPHP1g1

我的第二个问题是如何从构造函数中获取uid?因为我需要它从数据库中获取一些其他数据。

1 个答案:

答案 0 :(得分:2)

执行console.log("Test2...")时,该值尚不可用

当数据从服务器到达时,函数传递给subscribe()

    auth => {
      console.log(auth.uid);
      this.userid = auth.uid;
      console.log("Test 1 "+ this.userid);
    }

被调用,只有这样数据才可用,并且只有在该函数内,console.log("Test2 ...")在此之前执行了一段时间

export class DashboardComponent {
  userid:string;
  users:FirebaseListObservable<any[]>;
  constructor(public af: AngularFire) {
    this.af.auth.subscribe(auth => {
      console.log(auth.uid);
      this.userid = auth.uid;
      console.log("Test 1 "+ this.userid);
    });
    console.log("Test2 "+ this.userid);
  }
}