Obtain the $key item from the Firebase real-time database

Trying to implement dynamic routes in Realtime Database of Firebase based on the ID or $key of each object. Struggling to retrieve the ID, getting an undefined value. Any suggestions?

https://i.sstatic.net/IUwxJ.png

https://i.sstatic.net/K0de3.png

portafolio.component.html

<div class="container my-5">
<h1>Portafolio</h1>
<div class="row">
    <div class="col-md-4" *ngFor="let proyecto of proyectos | async">
        <div class="card my-3">
            <div class="card-body">
                <h4 class="card-title">{{ proyecto.titulo }}</h4>
                <a class="btn btn-primary" [routerLink]="['/portafolio', proyecto.$key]">Ver detalles</a>
            </div>
        </div>
    </div>
</div>

portafolio.component.ts

import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase, AngularFireList, AngularFireObject } from 'angularfire2/database';


@Component({
  selector: 'app-portafolio',
  templateUrl: './portafolio.component.html',
  styleUrls: ['./portafolio.component.scss']
})
export class PortafolioComponent implements OnInit {

  proyectos: any;

  constructor(private db: AngularFireDatabase) { }

  ngOnInit() {

      this.proyectos = this.db.list('proyectos').valueChanges();

  }

}

proyecto.ts

export interface Proyecto {
$key?: string;
titulo?: string;
destacado?: string;
descripcion?: string;}

Answer №1

Shoutout to @Hareesh for bringing up an interesting topic:

I found this solution effective:

portfolio.component.ts

import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase, AngularFireList} from 'angularfire2/database';
import { Observable } from "rxjs/Observable";

@Component({
  selector: 'app-portfolio',
  templateUrl: './portfolio.component.html',
  styleUrls: ['./portfolio.component.scss']
})
export class PortfolioComponent implements OnInit {

  allProjects: AngularFireList<any>;
  projects: Observable<any[]>;

  constructor(private db: AngularFireDatabase) { }

  ngOnInit() {
    this.allProjects = this.db.list('projects');

    this.projects = this.allProjects.snapshotChanges().map(changes => {
      return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
    });
  }
}

portfolio.component.html

<div class="container mt-5">
<h1>Portfolio</h1>
<div class="row">
    <div class="col-md-4" *ngFor="let project of projects | async">
        <div class="card my-3">
            <div class="card-body">
                <h4 class="card-title">{{ project.title }}</h4>
                <a class="btn btn-primary" [routerLink]="['/portfolio', project.key]">View details</a>
            </div>
        </div>
    </div>
</div>

Answer №2

To retrieve a specific property from an object, utilize square brackets as in project['$key']

<a class="btn btn-primary" [routerLink]="['/portfolio', project['$key']]">View details</a>

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

What are the steps for creating a standalone build in nextJS?

Currently, I am undertaking a project in which nextJS was chosen as the client-side tool. However, I am interested in deploying the client as static code on another platform. Upon generating a build, a folder with all the proprietary server elements of ne ...

Codelyzer is optimized for Angular 9 and doesn't currently support Angular 10

Whenever I run the command npm ls -json in my Node.js project, I encounter the following error: npm ERR! missing: @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e3d312c3b2e68797169717967">[email protected]< ...

Issue with Angular 7 Select directive failing to select an option that is loaded asynchronously

Currently, I am facing an issue with a select element in my form. The options of this select are generated through an http request. The problem arises when I use *ngFor to set the options tag based on the received data. Even though the first option appears ...

The Angular2 website is failing to update properly when utilizing Angular2-cli

Currently, I am in the process of developing a small Angular2 app and I am using WebStorm to make modifications to a file in order to see the updates reflect in my browser. So far, everything seems to be error-free as I have executed the following command ...

Weighing the importance of a multiple-choice quiz

I am faced with the challenge of assessing 25 multiple choice questions, each offering 4 answer choices worth varying points. Additionally, I have 2 free response questions that I wish to score based on the time taken to answer them. My proposed scoring ru ...

What is the process for removing a cookie in the MEAN stack?

I am facing an issue with deleting a cookie from my Node API in my Angular client (MEAN stack). On the Node side, I have a controller and a router set up, while on Angular, I subscribe to the service. // node router authRouter.get('/logout', t ...

The customized AgGrid template for displaying empty data sets is malfunctioning

Having some trouble with updating the overlayNoRowsTemplate when there is no data in the table. Here is the code snippet I am using: .ts export class AppComponent { rowData = [] columnDefs = [ { headerName: "ID", field: " ...

Filtering JSON data in Ionic 4 based on multiple values

Recently, I've encountered an issue with filtering a local JSON file based on multiple criteria. Initially, I thought that combining conditions using '&&' would solve the problem. However, when the data is loaded into Ngx-Datatable, nothing ...

The MatToolTip from Angular Material will only appear if the element is cut off

(Update: Urgent assistance needed! I am facing a critical issue. This problem persists, please check the comments for further details) I am seeking a solution to make the matTooltip appear only when the labels exceed their designated space limit. For inst ...

Display the year-month-day format as YYYY-MM-DD rather than the full date

Struggling to update a date linked by ngModel using ngx-bootstrap datepicker and send it in a PUT request to my Django backend. The date format keeps changing from YYYY-MM-DD (2019-08-13) to the full JavaScript date string (2019-08-13T23:00:00.000Z), causi ...

Angular: utilizing input type="date" to set a default value

Looking for a way to filter data by date range using two input fields of type "date"? I need these inputs to already display specific values when the page loads. The first input should have a value that is seven days prior to today's date, while the ...

Incoming information obtained via Websocket

Currently, I am working with Angular and attempting to retrieve data from the server using websockets. Despite successfully receiving the data from the server, I am faced with a challenge where instead of waiting for the server to send the data, it retur ...

Discover the most helpful keyboard shortcuts for Next.js 13!

If you're working with a standard Next.js 13 app that doesn't have the experimental app directory, setting up keyboard shortcuts can be done like this: import { useCallback, useEffect } from 'react'; export default function App() { c ...

Using a decorator with an abstract method

Discussing a specific class: export abstract class CanDeactivateComponent { abstract canLeavePage(): boolean; abstract onPageLeave(): void; @someDecorator abstract canDeactivateBeforeUnload(): boolean; } An error occurred stating that A decorat ...

Switch up the item's background in the dropdown list within Kendo UI Angular

Looking for a solution to highlight text and change background color in a dropdown list based on certain conditions. I searched the official Kendo forum without success. Any guidance or suggestions on how to resolve this issue would be greatly appreciate ...

The JWT Token is not being sent to the allowedDomain or whitelistedDomains in auth0/angular-jwt due to a configuration issue involving Regexp

Currently, I am utilizing the auth0/angular-jwt library to inject JWT tokens into my application. The documentation for this library suggests that configuration can be achieved by using strings or RegExp for specifying allowed domains. However, upon implem ...

Error message: Issue with TypeScript and cleave.js - 'rawValue' property is not found on type 'EventTarget & HTMLInputElement'

I am encountering an error with the onChange event while implementing cleave in typescript. TypeScript is throwing an error indicating that 'rawValue' is not present in event.target. Here is my code: import React, { useCallback, useState, useEff ...

The type 'Argument of (props: ITableProps) => JSX.Element' cannot be assigned to the parameter type of... - React High Order Component

One of the tools I have in my arsenal is a loader HOC This is how the HOC looks like: const withLoader = <P extends object>(WrappedComponent: new () => React.Component<P, any>, loading: boolean) => { return class WithLoading extends ...

Guide on setting up an onSnapshot listener with firestore in combination with express.js

Attempting to implement real-time functionality by adding an onSnapshot listener to a document. Everything functions correctly when the api is called, but any modifications to the data result in encountering the following: Error [ERR_HTTP_HEADERS_SENT ...

The React-native-vision-camera is unable to connect to the rear-facing camera

Currently, I am facing a challenge using the 'normal' camera on my iPhone 11 Pro. I have implemented react-native-vision-camera in my project. When executing the following code: const devices = useCameraDevices(); const deviceBack = devices.back; ...