UID is not displayed from the constructor

I have some problems trying to get uid from my constructor. When I run this code, the uid is displayed fine in the Test 1 log. However, the Test2 log shows it undefined. Does uid remove itself when closing the constructor?

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); } } 

this is my output in my console

 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 

My second question is: how can I get the uid from my constructor? Because I need to get some data from the database.

+5
source share
1 answer

When console.log("Test2...") is executed, the value is not yet available

When data comes from the server, the function is passed to subscribe()

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

only then the data becomes available and only inside this function, console.log("Test2 ...") was performed in absentia before

 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); } } 
+2
source

Source: https://habr.com/ru/post/1259499/


All Articles