Accessing the final element of an Observable<array[]> in Angular 5: A step-by-step guide

Currently, I am utilizing angularfire2 alongside Angular 5 for my project development. Below is the code snippet:

import { Component, OnInit } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument  } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';

export interface Details {
  name: string;
  phone: number;
  pphone: number;
  id: number;
}

@Component({
  selector: 'app-add-student',
  templateUrl: './add-student.component.html',
  styleUrls: ['./add-student.component.css']
})
export class AddStudentComponent implements OnInit {

  private studentCollection: AngularFirestoreCollection<Details>;
  students: Observable<Details[]>;

  constructor(db: AngularFirestore) {
    this.studentCollection = db.collection<Details>('collectionName');
    this.students = this.studentCollection.valueChanges();
  }

  ngOnInit() {
  }

I have a query regarding accessing the last JSON object stored in

students:Observable<Details[]>
. Is there any feasible method to achieve this? Apologies for any format inconsistencies in my post.

Answer №1

If you are looking to extract only the value

this.studentCollection.valueChanges().subscribe(info
                                  => console.log(info[info.length-1]))

If you prefer it in an observable form

Update: Added mergeAll() based on Aluan Haddad's suggestion

recentStudent$ = this.studentCollection.valueChanges().mergeAll().takeLast(1);

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

How can I display 4 react components, such as custom buttons, in a manner that ensures the most recently pressed button appears on top?

I've been attempting to solve this problem, but I'm struggling to find a solution. My current approach involves grouping the 4 button components in an array and shifting their positions based on user input. Is there a more efficient way to accomp ...

Encountering ExpressionChangedAfterItHasBeenCheckedError in Angular 17 even after invoking detectChanges method

I'm encountering a minor problem with Angular and its change detection mechanism. I have created a simple form where additional input fields can be added dynamically. However, every time I click the add button, an ExpressionChangedAfterItHasBeenChecke ...

Error: Serialization of circular structure to JSON not possible in Next.js

I am currently working on creating an API in Next.js to add data into a MySQL database. The issue I am facing is related to a circular reference, but pinpointing it has proven to be challenging. It's worth mentioning that Axios is also being utilized ...

Create a separate helper function to extract browser logs using Protractor's afterEach

My main objective is to create a helper function that extracts the browser.manage().logs() data. I am working towards this goal by incorporating the functionality of browser.manage().logs() within the afterEach method in my test script. I have noticed tha ...

In TypeScript and React, what is the appropriate type to retrieve the ID of a div when clicked?

I am facing an issue in finding the appropriate type for the onClick event that will help me retrieve the id of the clicked div. const getColor = (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => { const color = event.target.id; // ...

Continuing the process of uploading the file

In my development of a single page application that allows users to upload photos, I have encountered a dilemma. What happens if a user is uploading multiple photos and then closes the browser? When they log back in, I want the browser to automatically c ...

"Utilize XML parsing to convert data into JSON format and set up subscription functionality

My current task involves converting an XML string to JSON using xml2js. I then need to send and subscribe to the result in another component. getLastWeekSnow = function(){ let headers = new Headers(); headers.append('Access-Control-Allow-Origin' ...

What is the best way to restrict a React input field to have values within the minimum and maximum limits set by its

As a newcomer to React, I am working on restricting my input to values between -10 and 10. Currently, the input is set up to accept any value, and I am utilizing hooks like useState and useEffect to dynamically change and set the input value. My goal is ...

Encountering tsconfig.json issues following the integration of Tailwindcss v3 into Next.js (create-next-app --typescipt)

Upon opening my code in VS Code, I encountered the following error: Cannot find type definition file for 'accepts'. The file is in the program because: Entry point for implicit type library 'accepts' In an attempt to resolve this issue ...

Retrieve the chosen option from a dropdown list in Angular by utilizing reactive forms

I am facing an issue where I need to pass a hard coded value from a dropdown along with the input field values in my form. The problem arises because I am using formControlName to capture the input field values, but since there are no input fields in the d ...

An error in Webpack prevents it from resolving the data:text import

I built an app that relies on a third-party library with the following syntax: const module = await import(`data:text/javascript;charset=utf-8,${content}`); While using Webpack to build the app, I encountered this error: ERROR in ./node_modules/@web/test- ...

Discover the current routes in Angular

Looking for advice on creating a custom breadcrumb without data ID in the current routes. I have attempted the code below, but it includes the data ID and the routing is not functioning correctly. Seeking expert guidance. Actual link: http://localhost:4 ...

What is the best way to identify and process individual JSON objects separated by new lines in oboe's node-event within an Angular2 application?

I am working with an API that retrieves data in the following format: {"t":"point","id":817315,"tableid":141,"classid":142,"state":0,"loc":[6850735.34375,24501674.0039063]} {"t":"line","id":817314,"tableid":204,"classid":2102,"loc":[[6850335.8828125,24501 ...

The Postman application functions properly even though Unsupported Media Type 415 error occurred

Once a user has registered, they will receive a unique link containing their userId and a token. When the user clicks on this link, an Angular project will open and extract the userId and token from the link. This information is then sent via a post method ...

Exploring the differences: Async await, Promises, and Mapping

When faced with the decision between promises, async awaits, and mapping operators like concatMap, how do you determine which one to use? Specifically, I am working on a scenario where I need to make an http call to my backend, followed by another http ca ...

Interactive pie chart in Highcharts displaying real-time data fluctuations

I need to generate a dynamic pie chart using Highcharts, so I have created the following method: pieData: any = []; getPieData() { this.service.getSales().subscribe(data => { this.sales = data; for (var i = 0; i < this.sales.length; i++){ ...

Having trouble getting Next.js 404 page to function properly with the .tsx extension?

My latest project involved creating a Next.js application using regular JavaScript, which led to the development of my 404 page. 404.js import { useEffect } from "react"; import { useRouter } from "next/router"; import Link from " ...

What could be causing the vue-property-decorator @Emit to malfunction in my Vue TypeScript file?

I am currently working with Typescript and Vuejs, where I have a child component called child.component.tsx import Vue from 'vue'; import Component from 'vue-class-component'; import { Emit } from 'vue-property-decorator'; ...

Developing Components in Angular 2.0 with the assistance of ui-router

I am currently in the process of transitioning an Angular 1.x application to utilize Angular 1.5 components, a new feature that will be relevant for Angular 2.0. As far as I can tell, I need to create a Root Component that will serve as the main bootstrap ...

Encountering an error in Angular 8 where attempting to access an element in ngOnInit results in "Cannot read property 'focus' of null"

My html code in modal-login.component.html includes the following: <input placeholder="Password" id="password" type="password" formControlName="password" class="form-input" #loginFormPassword /> In m ...