Angular+Firebase技术求助:读取实时数据库最新数据并赋值distance变量实现单元格着色
Since you're working with observables (from valueChanges()), you need to subscribe to the observable to get the actual data and assign it to your local distance variable. Here's how to implement this step-by-step:
Step 1: Add Local Variables to Your Component
First, declare a distance variable to store the fetched value, and a subscription reference to clean up later (to avoid memory leaks):
import { Component, OnInit, OnDestroy } from '@angular/core'; import { AngularFireDatabase } from '@angular/fire/compat/database'; import { Observable, Subscription } from 'rxjs'; @Component({ // Your component metadata (selector, templateUrl, etc.) here }) export class YourComponent implements OnInit, OnDestroy { items: Observable<any[]>; distance: number = 0; // Initialize with a default value private itemsSubscription: Subscription; // Track the subscription for cleanup constructor(public db: AngularFireDatabase) {} // Your existing cells array and getCellColor method here cells= [ { id: 1, minDistance: 0.0, maxDistance: 1.4142135623730951 }, { id: 2, minDistance: 1.0, maxDistance: 2.23606797749979 }, { id: 3, minDistance: 2.0, maxDistance: 3.1622776601683795 }, { id: 4, minDistance: 3.0, maxDistance: 4.123105625617661 }, { id: 5, minDistance: 4.0, maxDistance: 5.0990195135927845 }, { id: 6, minDistance: 5.0, maxDistance: 6.082762530298219 }, { id: 7, minDistance: 6.0, maxDistance: 7.0710678118654755 }, { id: 8, minDistance: 7.0, maxDistance: 8.06225774829855 }, { id: 9, minDistance: 8.0, maxDistance: 9.055385138137417 }, { id: 10, minDistance: 9.0, maxDistance: 10.04987562112089 } ]; getCellColor(cell){ if (this.distance >= cell.minDistance && this.distance <= cell.maxDistance && this.distance > 0 ) { return "red"; } else{ return "green"; } } }
Step 2: Subscribe to the Observable to Fetch Data
In the ngOnInit lifecycle hook (better practice than using the constructor), subscribe to the items observable to get the latest distance value whenever Firebase updates:
ngOnInit() { this.items = this.db.list('DistanceVariationForDiffUserMockDataInfo', ref => ref.orderByChild("distance").limitToLast(1) ).valueChanges(); // Subscribe to the observable to access the actual data this.itemsSubscription = this.items.subscribe((data) => { // `data` is an array containing the last updated item (from limitToLast(1)) if (data.length > 0) { const latestEntry = data[0]; this.distance = latestEntry.distance; // Assign the fetched distance to your local variable console.log('Updated distance from Firebase:', this.distance); } else { console.log('No data found in the specified Firebase node'); } }, (error) => { console.error('Error fetching data from Firebase:', error); }); }
Step 3: Clean Up the Subscription
To prevent memory leaks when the component is destroyed, unsubscribe from the observable in ngOnDestroy:
ngOnDestroy() { if (this.itemsSubscription) { this.itemsSubscription.unsubscribe(); } }
Step 4: Use the Distance Value in Your Template
Your getCellColor method will now use the live distance value from Firebase. Make sure your template uses this method correctly, for example:
<!-- Example template loop to render cells --> <div *ngFor="let cell of cells" [style.backgroundColor]="getCellColor(cell)" class="cell-container"> Cell {{ cell.id }}: {{ cell.minDistance | number:'1-2' }} to {{ cell.maxDistance | number:'1-2' }} </div>
Key Notes:
- Asynchronous Data: Firebase data is fetched asynchronously, so subscribing is mandatory to access the actual value. The observable will automatically emit new data whenever the Firebase node is updated, keeping your
distancevariable in sync. - Error Handling: Added basic error handling in the subscription to catch any issues with fetching data from Firebase.
- Initial State: We initialized
distanceto 0, which means all cells will be green until the first data is fetched. If you want to handle this state differently (e.g., show a loading indicator), you can add anisLoadingvariable to track when data is being fetched.
内容的提问来源于stack exchange,提问作者Vinushi Lakshani

