Angular 为什么Firebase中的数据在刷新后立即加载?(角度)

Angular 为什么Firebase中的数据在刷新后立即加载?(角度),angular,firebase,firebase-realtime-database,google-cloud-firestore,Angular,Firebase,Firebase Realtime Database,Google Cloud Firestore,我正在用angular创建一个网站。 该站点包含一个登录页面,在用户登录后,会有一个到用户配置文件页面的路由,存储在Firebase中的数据将显示在该页面中 由于某种原因,数据在刷新页面后立即出现在屏幕上。 你知道原因是什么吗?我如何解决这个问题? 提前谢谢你 以下是我认为相关的代码: profile.component.html: auth.service.ts: crud.service.ts: login.component.ts: 这是因为subscribe in first返回null

我正在用angular创建一个网站。
该站点包含一个登录页面,在用户登录后,会有一个到用户配置文件页面的路由,存储在Firebase中的数据将显示在该页面中

由于某种原因,数据在刷新页面后立即出现在屏幕上。
你知道原因是什么吗?我如何解决这个问题?

提前谢谢你

以下是我认为相关的代码:

profile.component.html:

auth.service.ts:

crud.service.ts:

login.component.ts:


这是因为subscribe in first返回null或未定义
要解决此问题,您的代码如下:

  this.crudservice.get_userInfo().subscribe(data => {
         if(data != null && data != undefined) {
            this.user = data.map(c => {
              return {
                id: c.payload.doc.id,
                name: c.payload.doc.data()['name'],
                email: c.payload.doc.data()['email'],
                phone: c.payload.doc.data()['phone'],
              };
            })
            console.log(this.user); 
       }
     }
您还可以在HTML页面中添加ngIf

<div *ngIf="user != null" >
<h3 *ngFor="let item of user">Welcome back {{item.name}},</h3>
<h4>Your Details:</h4>
<table>
    <tbody *ngFor="let item of user">
        <div>
            <tr>
                <th>Name:</th>    
                <td>{{item.name}}</td>
            </tr>
            <tr>
                <th>Email:</th>   
                <td>{{item.email}}</td>
            </tr>
            <tr>
                <th>Phone Number:</th>   
                <td>{{item.phone}}</td>
            </tr>
        </div>
    </tbody> 
</table>
</div>

欢迎回到{{item.name},
您的详细信息:
姓名:
{{item.name}
电邮:
{{item.email}
电话号码:
{{item.phone}
详情如下:



希望有用

非常感谢您的回答!我根据您的建议更改了代码,但是在加载信息之前,我仍然需要刷新页面。这可能与我如何将登录页面导航到配置文件页面有关吗?(我在问题中添加了login.component.ts代码)我想导航没有问题!!!你有没有假设问题出在哪里@A.khalifaI认为this.authservice.currentUser尝试删除此代码,如果(this.authservice.currentUser!=null)//我们将确保用户已登录
import { Injectable } from '@angular/core';
import { AngularFireAuth} from '@angular/fire/auth';
import {Router} from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  authState: any =null;
  constructor(private afu: AngularFireAuth, private router: Router) {
    this.afu.authState.subscribe((auth =>{
      this.authState = auth;
    }))
  }
  //get fanctions, to get data from firebase
  get isUserAnonymousLoggedIn(): boolean{
    return (this.authState !== null) ? this.authState.isAnonymous : false
  } 
  get currentUserId(): string{
    return (this.authState !== null) ? this.authState.uid : ''
  } 
  get currentUserName(): string{
    return this.authState['email']
  } 
  get currentUser(): any{
    return (this.authState !== null) ? this.authState : null;
  } 
  get isUserEmailLoggedIn(): boolean{
    if((this.authState !== null) && (!this.isUserAnonymousLoggedIn)){
      return true
    } else{
      return false
    }
  } 
  //function in use in login.component.ts
  loginWithEmail(email: string, password: string){
    return this.afu.signInWithEmailAndPassword(email, password)
    .then((user) => {
      this.authState = user
    }).catch(error=>{
        console.log(error)
        throw error
      })
  }
}
import { Injectable } from '@angular/core';
import { from } from 'rxjs';
import {AngularFirestore} from '@angular/fire/firestore';
import { AuthService } from '../services/auth.service';

@Injectable({
  providedIn: 'root'
})
export class CrudService {

  constructor(private authservice: AuthService, public fireservices:AngularFirestore) { }
  
  get_userInfo()
  {
    return this.fireservices.collection('users').doc(this.authservice.currentUserId).collection('user-info').snapshotChanges();
  }
}
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../services/auth.service';
import {Router} from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  email="";
  password="";
  errorMessage = ''; //validation error handle
  error: {name:string, message:string} = {name:'' , message:''}; //firebase error handle

  constructor(private authservice: AuthService, private router: Router) { }
  
  ngOnInit(): void {
  }

  login()
  {
    this.clearErrorMessage();
    if(this.validateForm(this.email, this.password))
    {
      this.authservice.loginWithEmail(this.email, this.password)
      .then(() => {
        this.router.navigate(['/profile'])
      }).catch(_error =>{
        this.error = _error
        this.router.navigate(['/login'])
      })
    }  
  }

  clearErrorMessage()
  {
    this.errorMessage = '';
    this.error = {name: '', message:''};
  }

  validateForm(email, password)
  {
  .
  .
  .
  .
  }
}
  this.crudservice.get_userInfo().subscribe(data => {
         if(data != null && data != undefined) {
            this.user = data.map(c => {
              return {
                id: c.payload.doc.id,
                name: c.payload.doc.data()['name'],
                email: c.payload.doc.data()['email'],
                phone: c.payload.doc.data()['phone'],
              };
            })
            console.log(this.user); 
       }
     }
<div *ngIf="user != null" >
<h3 *ngFor="let item of user">Welcome back {{item.name}},</h3>
<h4>Your Details:</h4>
<table>
    <tbody *ngFor="let item of user">
        <div>
            <tr>
                <th>Name:</th>    
                <td>{{item.name}}</td>
            </tr>
            <tr>
                <th>Email:</th>   
                <td>{{item.email}}</td>
            </tr>
            <tr>
                <th>Phone Number:</th>   
                <td>{{item.phone}}</td>
            </tr>
        </div>
    </tbody> 
</table>
</div>