Ways to showcase product information (Using Angular and Firebase)

Information product.model.ts

  id?: string;
  name: string;
  price: number;
  sale_price: number;
  description: string;
  tech_sheet: string;
  imageUrls: string[];
  category: string;
  createdAt: Date;
}

Initialize file product.service.ts The latest function

getDetailProduct(productId: string)
is used to fetch a product using its ID.

import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/compat/firestore';
import { Observable } from 'rxjs';
import { Product } from 'src/app/models/product.model';

@Injectable({
  providedIn: 'root'
})
export class ProductsService {

    productCollection: AngularFirestoreCollection<Product>;
    
    constructor(private dbstore: AngularFirestore) {
      this.productCollection = this.dbstore.collection('products', (ref) => 
        ref.orderBy('name', 'desc')
      );
    }

    addProduct = (product: Product) => this.productCollection.add(product);


    getProducts() {
      return this.dbstore.collection('products').snapshotChanges();
    }

    getDetailProduct(productId: string): Observable<Product | undefined> {
      return this.productCollection.doc(productId).valueChanges();
    }

}

Invoke the function in the product.service.ts service to access the detailed product page with the ID.

  goToDetailsProduct(productId?: string): void {
    this.router.navigate(['product-details', productId]);
    console.log(productId);
  }

When clicking on a product, the link containing its ID should be included in the URL.

<div class="card card-shopping" *ngFor="let product of products" (click)="goToDetailsProduct(product.id)">

Issue: How can we retrieve all product data and display it on the page details-product.component.ts?

import {Location} from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';
import { Product } from 'src/app/models/product.model';
import { ProductsService } from '../../shared/services/products.service'


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

  productIdRoute?: string;
  product?: Observable<Product | undefined>;

  constructor(
    private location: Location,
    private route: ActivatedRoute,
    private productService: ProductsService
  ) {
    const routeParams = this.route.snapshot.paramMap;
    this.productIdRoute = String(routeParams.get('productId'))
    this.product = this.productService.getDetailProduct(this.productIdRoute);
  }

  ngOnInit(): void {
  }

  // goBack = () => this.location.back();

}


Answer №1

It seems like you are looking to display detailed data in a component by passing an ID through a URL. Here are two scenarios you can use to retrieve the data:

  1. Call the Firebase function to get a single data instance inside the detail page.

In your constructor, make sure to initialize the Route parameter object as follows:

    constructor(private route: ActivatedRoute) 

Add this code snippet inside your onInit method:

this.route.params.subscribe(() => {this.id = this.route.snapshot.params["id"];});
// Replace "id" with your query parameter name.

Once you have obtained the ID through parameters, you can call the Firebase function to fetch the instance:

this.afs.collection('collection_name')
  .doc(id)
  .ref;
  1. You also have the option to pass data via Route parameters. On your products page, pass the data using:

      this.router.navigate(['/about'], {
       state: {
         data: JSON.stringify({ name: 'Angular', detail: '1' })}
     });
    

In your detail page, you can access the passed data like this:

    constructor(private router: Router) {
    if (this.router.getCurrentNavigation().extras.state) {
      this.routeState = this.router.getCurrentNavigation().extras.state;
  if (this.routeState) {
    this.data.frontEnd = this.routeState.frontEnd ? JSON.parse(this.routeState.data) : '';
    this.data.site = this.routeState.site ? this.routeState.site : '';
  }
}}

I recommend going with the first scenario as it is more straightforward to work with.

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

"Troubleshooting the issue of Angular's ng-selected not functioning properly within an edit

https://i.stack.imgur.com/ZpCmx.png https://i.stack.imgur.com/h3TA6.png TS Pincodes: Array<string> = []; Html <ng-select [items]="Pincodes" [searchable]="true" [multiple]="true" [(ngModel)]="updateZoneDetails ...

Ensure that the hook component has completed updating before providing the value to the form

Lately, I've encountered an issue that's been bothering me. I'm trying to set up a simple panel for adding new articles or news to my app using Firebase. To achieve this, I created a custom hook to fetch the highest current article ID, which ...

Generate a list of items in typescript, and then import them into a react component dynamically

I have a variable that stores key/value pairs of names and components in a TypeScript file. // icons.tsx import { BirdIcon, CatIcon } from 'components/Icons'; interface IconMap { [key: string]: string | undefined; } export const Icons: IconM ...

Angular Binding issue - Unable to bind to 'ngModel' as it is not recognized as a valid property of 'input' element, despite the property being present

I have developed a component class like the one below and I am attempting to link the class fields to the template, but encountered the following error: ERROR in src/app/admin/projects/projects.component.html: 41:34 - error NG8002: Can't bind to &ap ...

Distribute among an array of specific types

I am trying to achieve this behavior using Typescript: type animals = 'cat' | 'dog' let selectedAnimals: animals[] = ['cat'] selectedAnimals = [ // <- Type 'string[]' is not assignable to type 'animals[]&ap ...

Displayed even when data is present, the PrimeNg empty message persists

I have set up a PrimeNg table to display data with an empty message template like this: <ng-template pTemplate="emptymessage"> <tr> <td> No records found </td> </tr> </ng-template> ...

The local scope in Angular is inaccessible within an observable subscription

I've been grappling with this issue for quite some time and have experimented with numerous solutions. It seems that within my subscribe function, I'm unable to access ChangeDetectorRef or NgZone in order to trigger an update on the scope. Why ...

Using a React component with Material-UI style classes in TypeScript is not possible

Recently delving into react, I've embarked on a learning project utilizing typescript 3.7.2 alongside material-ui 4.11.0 and react 16.13.1. Initially, I structured my page layouts using functional components, but upon attempting to switch them to clas ...

What's New with Material 3 in Angular 17?

Even though I've taken the time to read all of the documentation at https://github.com/material-components/material-web/blob/main/docs/quick-start.md, I'm still struggling to figure out how to incorporate this into my Angular 17 project. I went ...

Angular - optimize performance of vm-ware datagrid by using clrDgRefresh with debounce for improved

Is there a way to delay an event triggered by the clarity datagrid until after the user has finished typing before fetching data from the backend? My angular 6 application uses the grid, and I bind the event to a function in my setup like this: <clr-da ...

execute the node application using the .desktop file

Hello, I am attempting to launch an application in Linux by double-clicking it. I have come across the .desktop file as a solution (I need this method because the app will be deployed on a Raspberry Pi and users prefer not to use the terminal). Here is wha ...

Using ngFor to create dynamic columns in a Kendo Grid

Looking at this code snippet <kendo-grid-column title="{{localizationKeys.adempimenti.organizzazione.responsabile}}" field="addettiGrid"> <li *ngFor="let addetto of addettiGrid; let i=index"> <div>{{addetto}}</div> ...

There was a serious issue: The mark-compacts were not working effectively near the heap limit, resulting in allocation failure - the JavaScript heap ran out of memory during the

I recently set up a t2.micro server on AWS and encountered an issue when running our application with the command "sudo npm start". The error message I received was: "FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript he ...

Unlocking the Magic: A Step-by-Step Guide to Generating PDFs with

I'm currently engaged in developing an IONIC venture employing JavaScript and Angular. One of the tasks entails creating a comprehensive PDF report featuring text, images, and graphs. Instead of hand-crafting all the elements, I'm keen on adoptin ...

What is the best way to apply ngClass to style a JSON object based on its length?

Currently, I am working with a mat-table that displays data from a JSON object. My goal is to filter out all records with an ID of length 5 and then style them using ngClass in my HTML template. How can I achieve this? Below is the code I am working with: ...

Issues Arise with Nativescript Layout When Content is Not in View on iOS

This problem has been giving me a hard time for the past few days. I hope someone can help me figure out what's wrong. I have a view that shows a nested list inside a main list. The main list contains header details. Everything looks fine when the in ...

Running into an issue while attempting to update a Firebase array using the .where() method. The error message states that ".update isn't

I'm currently in the process of updating a document in my Firebase that contains an array. At this point, a user's document might appear as follows: username: John postedProjects: ['project-one', 'project-two'] As John subm ...

Why is NestJs having trouble resolving dependencies?

Recently delving into NestJs, I followed the configuration instructions outlined in https://docs.nestjs.com/techniques/database, but I am struggling to identify the issue within my code. Error: Nest cannot resolve dependencies of the AdminRepository ...

Issues with updating in Firebase real-time database using Angular 2 are not

I am currently working on a simple app that inserts new records into Firebase. Below the input field, the app lists the last 10 items in the database. ISSUE: I am facing a problem where I have to start inputting something in the input field or click on ...

Angular transforming full names to initials within an avatar

What is the best way to convert names into initials and place them inside circular icons, like shown in the screenshot below? I already have code that converts the initials, but how do we create and add them inside the icons? The maximum number of icons di ...