UID没有显示构造函数

Dyl*_*mes 5 authentication firebase angularfire angular

我试图让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);
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我在控制台中的输出

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
Run Code Online (Sandbox Code Playgroud)

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

Gün*_*uer 2

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

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

    auth => {
      console.log(auth.uid);
      this.userid = auth.uid;
      console.log("Test 1 "+ this.userid);
    }
Run Code Online (Sandbox Code Playgroud)

被调用,只有这样数据才变得可用,并且仅在该函数内,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);
  }
}
Run Code Online (Sandbox Code Playgroud)