show the updated value of a created array after angular firestore subscription

Issue

i want to access the content of a variable i filled with an array of an firebase subscription, my problem is i cant/dont know how to access/get the value which i created inside the subscription. it feels like i cant use the created value outsite of the subcription(from angularfirestore)

import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { AuthService } from "../../services/auth.service";

@Component({
  selector: 'app-sign-in',
  templateUrl: './sign-in.component.html',
  styleUrls: ['./sign-in.component.scss']
})
export class SignInComponent implements OnInit {
  email = new FormControl('', [Validators.required, Validators.email]);
  users2: any[] = [];
  constructor(public authService: AuthService) {
}

ngOnInit(): void {
  this.getUsers2();
  console.log("show-res??",this.users2) //not showing the filled array only an empty one
  
}

getUsers2(){
     this.authService
     .getCollection2("users")
     //.subscribe(res =>(console.log("show-res",res)))//her shows the res i need
     .subscribe((res: any[])=>{(this.users2 =res)})        
}

}


//auth.service.ts file
...
  getCollection2(collection: string) {
    return this.afs.collection(collection).valueChanges(); 
  }
...

Solution

When your getUsers2 function is called it waits a response from server/api and js/ts doesn’t wait it because it is asynchronous and continue to executing other lines. When js/ts execetus your console.log("show-res??",this.users2) function and you see empty array because api respınse hasn’t assigned to users2 array. So, if you want to log your user just do it in your getUsers2 function.

import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { AuthService } from "../../services/auth.service";

@Component({
  selector: 'app-sign-in',
  templateUrl: './sign-in.component.html',
  styleUrls: ['./sign-in.component.scss']
})
export class SignInComponent implements OnInit {
  email = new FormControl('', [Validators.required, Validators.email]);
  users2: any[] = [];
  constructor(public authService: AuthService) {
}

ngOnInit(): void {
  this.getUsers2();
  
}

getUsers2(){
     this.authService
     .getCollection2("users")
     .subscribe((res: any[])=>{
        this.users2 =res//
        console.log("show-res??",this.users2);
     })        
}

printUser(){//call this from ui with button click
    console.log(this.user2);
}


}

If you want to print user data you can add a button on ui and set its click event to printUser function.

<button (click)="printUser()">Print User</button>

or show your user on ui with *ngFor

<ul>
   <li *ngFor="let user of user2" >{{user.name}}</li> 
</ul>

Answered By – Barış Can Yılmaz

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.