What is the best way to retrieve the most recent entry in a Firebase real-time database?

Utilizing Firebase's real-time database, I am updating values in a chart as they change. However, my struggle lies in retrieving only the most recent value added to the database.

While browsing through limitToLast and 'child_added' do not work together #1773, I attempted to implement some suggestions but couldn't get it to function properly.

Currently, this is what I have managed to achieve:

this.items = db.list('/items').valueChanges()
this.items.forEach(item => {
  this.data = item;
  this.add(this.data[this.data.length-1])
  console.log(this.data)
})

add(point: any) {
   this.chart.addPoint(point)
}

Realistically, I am aware that this approach is far from efficient.

Answer №1

According to the information found in the documentation:

list<T>(pathOrRef: PathReference, queryFn?: QueryFn): AngularFireList<T> {
 const ref = getRef(this.database, pathOrRef);
 let query: DatabaseQuery = ref;
 if(queryFn) {
   query = queryFn(ref);
 }
 return createListReference<T>(query, this);
}

The method list() allows for querying with a second parameter, as shown below:

this.items = db.list('/items', ref => ref.limitToLast(2)).valueChanges()

// Subscribe to changes
this.items.subscribe(lastItems =>{
  console.log(lastItems);  
});

The use of valueChanges() will provide an Observable that can be subscribed to in order to receive values.

For further details, please refer to:

https://github.com/angular/angularfire2/blob/master/docs/rtdb/querying-lists.md

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Set an enumerated data type as the key's value in an object structure

Here is an example of my custom Enum: export enum MyCustomEnum { Item1 = 'Item 1', Item2 = 'Item 2', Item3 = 'Item 3', Item4 = 'Item 4', Item5 = 'Item 5', } I am trying to define a type for the f ...

"Using Angular and TypeScript to dynamically show or hide tabs based on the selected language on a website

When switching the language on the website, I want to display or hide a specific tab. If the language is set to German, then show the tab; if any other language is selected, hide it. Here's my code: ngOnInit(): void { this.translate.onLangChange.s ...

Setting the [required] attribute dynamically on mat-select in Angular 6

I'm working on an Angular v6 app where I need to display a drop-down and make it required based on a boolean value that is set by a checkbox. Here's a snippet of the template code (initially, includeModelVersion is set to false): <mat-checkbo ...

Issue with string interpolation failing to correctly reflect the updated value from the service provider

I created a simple component to test string interpolation in HTML, <p>{{value}}</p> Here is the TypeScript file: export class HelloComponent implements OnInit { value: any; constructor(private service: ApiService) { this.value = ...

Excessive recursion detected in the HttpInterceptor module

My application uses JWT tokens for authentication, with a random secure string inside the JWT and in the database to validate the token. When a user logs out, a new random string is generated and stored in the database, rendering the JWT invalid if the str ...

Adding Angular to your current project involves integrating the framework into your

Previously, the task of initializing a project was done using ng init, but that command no longer exists. Another option is to run ng new from a higher level in the directory structure and specify the folder for your existing project. However, this will ...

Tips for maintaining selected text while a modal window is active

So I'm currently working on a document writer and I'm utilizing document.execCommand to insert links. What I aim for is the ability for a user to select/highlight text, click a button to add a link to that specific text (via a modal), and then ha ...

Obtaining a binary value in the switch component of materialize framework with Typescript

Is there a way in Typescript to assign a value of 1 when a checkbox is checked and 0 otherwise? I am working on a project that uses the materialize framework. Below is the code snippet in question: <div class='switch'> <label&g ...

establishing the default value as p-multiselect

Here is the code snippet I am currently working on: export class LkBoardStatus { id : number = 0; descr : string = ''; } In the component.ts file, I have defined the following: //... lkBoardStatusList: LkBoardStatus[] = []; selectedStat ...

Attempting to leverage the combination of mocha, ES6 modules, and ts-node while utilizing the --experimental-loader option

I've been attempting to make the ts-node option --experimental-loader function alongside mocha, but so far I haven't had any success. Before I started compiling ES6 modules, running mocha tests was as simple as: "test": "nyc --reporter=html mocha ...

The Java Spring and Angular 7 application is missing a necessary file request component

I am facing an issue with the POST method in Angular 6. I am trying to send an image to the server. When I test it using Postman, my Spring Boot application works perfectly and saves the image on the server. However, when I attempt to send the image from m ...

What situations call for the use of 'import * as' in TypeScript?

Attempting to construct a cognitive framework for understanding the functionality of import * as Blah. Take, for instance: import * as StackTrace from 'stacktrace-js'; How does this operation function and in what scenarios should we utilize imp ...

What exactly occurs when a "variable is declared but its value is never read" situation arises?

I encountered the same warning multiple times while implementing this particular pattern. function test() { let value: number = 0 // The warning occurs at this line: value is declared but its value is never read value = 2 return false } My curi ...

Display a slideshow of images using the text and <img> tags found within a string in an Angular application

Currently, I am developing a blog system in Angular that involves utilizing a text editor component (ngx-text-editor) for inserting images and text. These images and text are then saved to the database. However, I am facing an issue when attempting to disp ...

TS - Custom API hook for making multiple API requests - incompatible type with 'IUseApiHook'

What is my objective? I aim to develop a versatile function capable of handling any type of API request for a frontend application. Essentially, I want to add some flair. Issue at hand? I find myself overwhelmed and in need of a fresh perspective to revi ...

What is the best way to exclude a particular subtype or property?

Is there a way to exclude a specific nested property? Let's take a look at an example. interface ILikes { article: string, page: string, userId: number | string, } interface IUserData { userName: string, isAdmin: boolean, ...data, ...

I'm new to Angular, so could you please explain this to me? I'm trying to understand the concept of `private todoItems: TodoItem[] = []`. I know `TodoItem` is an array that

//This pertains to the todoList class// The property name is todoItems, which is an array of TodoItem objects fetched from the TodoItem file. I am unable to make it private using "private todoItems: TodoItem[] = []," is this because of Dependency Injectio ...

Is there a way to use Jest spyOn to monitor a function that is returned by another function?

I'm curious about why the final assertion (expect(msgSpy).toBeCalled()) in this code snippet is failing. What adjustments should be made to ensure it passes? it('spyOn test', () => { const newClient = () => { const getMsg = ...

Looking for guidance on implementing explicit waits in Protractor for non-angular applications

I have noticed that automating non-angular applications with Protractor can be challenging. Currently, I am using some methods to add an explicit wait to my existing Serenity click and enter functions. However, I am curious if there is a way to automatic ...

Attempting to ensure that Angular 2 delays rendering until the necessary data has finished loading

Looking to efficiently load multiple XML files before the initial rendering? Here's a configuration snippet from app.module.ts: import { DataProvider } from './xml-provider' export function dataProviderFactory(provider: DataProvider) { r ...