在 angular firestore 订阅后显示已创建数组的更新值

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

我想访问我用 firebase 订阅数组填充的变量的内容,我的问题是我 cant/dont 知道如何 access/get 我在订阅中创建的值。感觉我不能在订阅之外使用创造的价值(来自 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(); 
  }
...

当您的 getUsers2 函数被调用时,它等待来自 server/api 的响应,而 js/ts 不等待它,因为它是异步的并继续执行其他线路。当 js/ts 执行您的 console.log("show-res??",this.users2) 函数时,您会看到空数组,因为 api 响应尚未分配给 users2 数组。因此,如果您想记录您的用户,只需在 getUsers2 函数中执行即可。

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


}

如果要打印用户数据,可以在 ui 上添加一个按钮并将其点击事件设置为 printUser 函数。

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

或使用 *ngFor

在 ui 上向您的用户展示
<ul>
   <li *ngFor="let user of user2" >{{user.name}}</li> 
</ul>