I want to know the most effective way to showcase particular information on a separate page using Angular

Recently, I've been working with a mock json file that contains a list of products to be displayed on a Product page. My goal is to select a specific product, such as 'Product 1', and have only that product's information displayed on the Product Detail page. However, I'm encountering issues where the Product Detail page is showing information for all products and not properly displaying the selected product's name. As a self-taught individual, I'm unsure if the mistake lies within the typescript or json file. Can someone help point me in the right direction to resolve this issue?

Here is the code snippet:

product.component.html

<h4>Department 1</h4>
<div class="application-card" routerLink="/productDetails"
  *ngFor="let product of products; let i = index">
  {{ product.product_name }}
  </div>

product.component.ts

import { Component, OnIt } from '@angular/core';
import {HttpClient} from "@angular/common/http";

@Component ({
  selector: 'app-product',
  templateURL: './product.component.html',
  styleURLs: [./product.component.css']
})

export class ProductComponent implements OnInit {
  products: any ""

  constructor(private http: HttpClient) {}
  
  ngOnInit(): void {
   this.allProducts();
  }

  allProducts() {
    this.http.get<ProductList>(url: 'http://localhost:3000/productList).subscribe(next: data => {
     this.products = data;
    })
   }

}

interface ProductList {
  product_name: string;
  product_detail_1: string;
  product_detail_2: string;
  product_detail_3: string;
}

productdetails.component.html

<h1>Product Details - {{ product.product_name }}</h1>

<p *ngFor="let product of products">
  {{ product.product_details_1 }}
  {{ product.product_details_2 }}
  {{ product.product_details_3 }}
</p>

productdetails.component.ts

import { Component, OnIt } from '@angular/core';
import {HttpClient} from "@angular/common/http";

@Component ({
  selector: 'app-productdetails',
  templateURL: './productdetails.component.html',
  styleURLs: [./productdetails.component.css']
})

export class ProductDetailsComponent implements OnInit {
  products: any ""

  constructor(private http: HttpClient) {}
  
  ngOnInit(): void {
   this.allProducts();
  }

  allProducts() {
    this.http.get<ProductList>(url: 'http://localhost:3000/productList).subscribe(next: data => {
     this.products = data;
    })
   }

}

interface ProductList {
  product_name: string;
  product_detail_1: string;
  product_detail_2: string;
  product_detail_3: string;
}

products.json

{
   "productList": [
   {
     "product_name": "Product 1",
     "product_details_1":  "1st detail about Product 1",
     "product_details_2":  "2nd detail about Product 1",
     "product_details_3":  "3rd detail about Product 1"
   },
   {
     "product_name": "Product 2",
     "product_details_1":  "1st detail about Product 2",
     "product_details_2":  "2nd detail about Product 2",
     "product_details_3":  "3rd detail about Product 2"
   },
   {
     "product_name": "Product 3",
     "product_details_1":  "1st detail about Product 3",
     "product_details_2":  "2nd detail about Product 3",
     "product_details_3":  "3rd detail about Product 3"
   },


Answer №1

Within your product.component.html file, the code is iterating through the products list and retrieving each product's index without utilizing it for anything significant. When transitioning to the product details component, this particular component lacks direction on what content to display. To rectify this issue, consider incorporating a mock endpoint, such as /productDetails/0 for the first item in the array.

To integrate the endpoint into your routing setup - assuming you are working with app.component-routing.ts - proceed as follows:

  1. Revise your productDetails route to resemble the following structure:

    { path: '/productDetails/:id', component: ProductDetailsComponent}

  2. Inside your productdetails.component.ts file, adhere to these steps.

Step 1: Import ActivatedRoute

import { ActivatedRoute } from '@angular/router';

Step 2: Inject ActivatedRoute within the constructor.

constructor(private activatedRoute: ActivatedRoute) { }

Step 3: Capture the id in a local variable within ngOnInit() or the constructor {}

const productId = this.activatedRoute.snapshot.params['id'];
  1. Proceed to filter your products by the id retrieved and you are all set.

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

Angular Signal computation does not initiate a re-render

I am currently working on sorting an array of signals within my component. To achieve this, I have wrapped the array in a compute function that sorts it. Below is the relevant code snippet: In the Service file: private readonly _lobbies = signal<Lobby ...

Encounter the warning message "EBADENGINE does not support engine @angulardevkit" while attempting to install class-validator and class-transformer with NestJS

Currently, I am going through the NestJS website course and I encountered an issue while trying to install class-validator and class-transformer using npm i class-validator class-transformer Upon running the command, I received the following error: npm WA ...

Eliminating Redundant Quotation Marks in JSON Data with Scala

I've been attempting to sanitize my JSON object using Scala, but I'm struggling to eliminate the extra quotes from my JSON value. For example, "LAST_NM":"SMITH "LIBBY" MARY" The presence of additional commas within my string is causing issues. ...

Angular: How to restrict the compilation of rgba() to #rrggbbaa in your codebase

There are some browsers that do not support #rrggbbaa but do support rgba(). However, in my Angular project, background-color: rgba(58, 58, 58, 0.9) in common.css was compiled to background-color:#3a3a3ae6 in style.[hash].css. How can I prevent this co ...

Tips for incorporating momentjs into TypeScript within AngularJS 1.5

I am looking to integrate the momentJs library into my TypeScript code for Date object operations. However, I need some guidance on how to inject TypeScript in AngularJS, as it differs slightly from JavaScript. angular.module("app") .config(functio ...

The absence of the Angular property has been detected

Let's say you have the following model in your application. export class Instructor{ firstname:string; lastname:string; } export class Course { ID: number; title: string; crn: string; instructor:Instructor; } In order to reset a form, you can us ...

JavaScript issue: Shallow copy does not reflect updates in nested JSON object

Within my coding project, I came across a nested JSON object that looks like this: var jsonObj = { "level1" : { "status" : true, "level2" : {} // with the potential to extend further to level 3, 4, and beyond } } My objective is si ...

The type 'any' cannot be assigned to the type 'never' as a parameter

const [files, setFiles] = useState([]) const handleChange = (event: any) => { setFiles.push(event.target.files[0].name) return (<div> {files.map((file: any) => ( <p>Hello!</p> ))} </ ...

retrieve a stream of data from a subscription

After conducting various experiments, I decided to share the code in its original form to determine the best practice: Within a function (in the service), I subscribe to a result as a BLOB and save it as content of a file on the local file system using Fil ...

Leveraging Golang's GORM for Efficient JSON Decoding from HTTP Request Body

I am encountering an issue while attempting to decode a JSON request using gorilla/mux into a struct and then saving it with GORM into a MySQL database. The request, sent via cURL (refer to the cURL command), is invalid and should fail at two points: 1) It ...

The information is being properly displayed in the console, but when attempting to show it on the webpage, an ERROR occurs with the message: "Error trying to differentiate '[object Object]'"

The data is successfully displayed in the console. However, when trying to display it on the page, an error occurs: ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed services getdetails(id:number) : ...

Kendo: linking information to a form

I recently inquired about this matter on Stack Overflow but wanted to share my question here as well. Due to my limited reputation, I am unable to leave a comment, so please excuse any redundancies. My current challenge is figuring out how to bind the re ...

Confirm button title by verifying part of the label that contains a space

I'm facing an issue with clicking a button using the following code: await page.getByRole('button', { name: '3 Employees' }).click(); The problem is that the button's name fluctuates based on the number of employees, causing ...

Redux ConnectedProps will always have a type of never

I am facing an issue while attempting to connect a component to my Redux store following the steps outlined in the official documentation guide. The props that are connected seem to be coming through as type never. Here is a snippet of my code: Type defi ...

Animated scrolling in Angular

I am working on a webpage using Angular, where each module is a component with an animation. However, I am facing an issue where the animation only runs when the page loads, but I want it to happen while the component is visible on the screen. One approa ...

Attempting to decode JSON data in AppleScript with the help of JSONHelper

Using AppleScript can sometimes feel as easy as plain English, but I often wish it was even simpler, like being able to type: somearray.someotherarray.0.item Nevertheless, here is the code snippet at hand: set q to "Terminator" tell application ...

Tips for locating the beginning and conclusion of a RxJS.ajax request?

I'm utilizing the RxJS.ajax call to verify the availability of a product in the database. The response from this call typically takes between 2 to 4 seconds. During that retrieval time, I would like to show a message indicating "searching for product" ...

Angular Compilation Errors Caused by Component Inheritance

My parent Component is structured like this: import { Component} from '@angular/core'; @Component({ selector: 'app-main-parent', template: '', }) export class ParentComponent { constructor(protected service) { ...

Assigning values from JSON data in jQuery

I'm facing an issue with a php query that outputs json containing a single value. The json data format is as follows: {"value":53}. I've been attempting to set this value as a variable in a jquery function, but have not been successful so far des ...

Determine the class of an object within the "keyof" parameter by utilizing both property and generic types

I have a requirement to create an interface with generic types that can accept an object with keys representing "root field names" and values as arrays of objects defining sub-fields with the key as the name of the sub-field and the type as the value' ...