【问题标题】:Data not getting updated in Angular when fetched from Firebase RealTime Database从 Firebase 实时数据库中获取数据时,Angular 中的数据未得到更新
【发布时间】:2020-03-29 23:24:37
【问题描述】:

当我从firebase.service.ts 提供静态数据时刷新HTML 内容,但是当我从firebase 获取数据时,我无法显示内容。

为了调试,我提供了静态和 firebase 数据。所以静态数据被显示,但是firebase数据,思想被记录到控制台,永远不会到达页面的html。

我尝试添加一些 console.logs() 来调试代码。我还添加了 cmets 以指示执行 console.log() 语句的顺序。

firedb.service.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
import { of } from 'rxjs'; 

@Injectable({
  providedIn: 'root'
})

export class FiredbService {
  constructor(private firestore: AngularFireDatabase) { }
  public getMovies(){
    let movies;
    let dbref = this.firestore.database.ref();
    dbref.once('value', function(snapshot) {
      snapshot.forEach(function(childSnapshot) {
        movies = childSnapshot.val();
        console.log(movies); //This prints last but page doesnt refresh
      });
    });
    console.log("Before Return") //This prints first
    console.log(movies); //This prints second as undefined
    movies = [{"title":"Inception","year":"2010"},{"title":"Inception","year":"2010"}];
    return of(movies);
  }
}

电影列表.component.ts

import { Component, OnInit } from '@angular/core';
import { FiredbService } from '../firedb.service';

@Component({
  selector: 'movie-list',
  templateUrl: './movie-list.component.html',
  styleUrls: ['./movie-list.component.css']
})

export class MovieListComponent implements OnInit {
  movies;
  constructor(private firestore: FiredbService) { }
  ngOnInit() {
    this.firestore.getMovies().subscribe(data => this.movies = 
      data);
    console.log("Inside Component"); //This prints third
    console.log(this.movies);  //This prints fourth, static content from firedb.service
  }
}

调试器控制台

Before Return      (from firedb.service)
undefined          (from firedb.service)
Inside Component   (from the movie-list.component)
[{…}, {…}]         (from the movie-list.component)
[1: {…}, 2: {…}, 3: {…}, 4: {…}, ......., 10000:{…}]  (from firedb.service)

【问题讨论】:

    标签: angular firebase-realtime-database


    【解决方案1】:

    这是因为角度变化检测策略。您需要从组件中的@angular/core导入ChangeDetectorRef。然后你需要从构造函数中注入它。从 firebase 获取数据后,您需要调用 detectChanges() 方法。

    构造函数示例代码

    constructor(
        private _changeDetectionRef: ChangeDetectorRef
        ) 
        {
    
         }
    

    带有变更检测的 http 调用示例

    getPractices() {
    
        this._clientService.getList(0, 100)
          .subscribe(result => {
    
            if (result != null && result.items.length > 0) {
              this.practices = result.items;
            }
           this._changeDetectionRef.detectChanges();
          })
      }
    

    【讨论】:

      猜你喜欢
      • 2021-10-04
      • 2019-01-17
      • 1970-01-01
      • 2023-01-17
      • 1970-01-01
      • 2021-03-04
      • 2022-07-08
      • 1970-01-01
      • 2022-08-17
      相关资源
      最近更新 更多