How do I display a single record from an array object in Angular?

Encountering a dilemma when attempting to retrieve a single record from an array like this

data.service.ts

    getOneBookDetail(isbn:any) {
        const headers = new HttpHeaders().set("Content-Type", "application/json");
    
        // console.log("=============" + isbn )
        console.log(headers)
        return this.http.get('http://localhost:10888/bookdetail/?isbn='+ isbn).subscribe(
          (val) => { // Get has no error and response has body
            console.log("Get successful value returned in body", val);
          },
          response => {
            console.log("Get call in error", response);
          },
          () => { // Get has no error, response has no body
            console.log("The Get observable is now completed.");
          });
      }

home.component.ts
getBookDetail(book) {
    this.data.getOneBookDetail(book.isbn)   //isbn of book
   }

and I can click the title of book

 <a routerLink="/bookdetail/{{book.isbn}}" (click)="getBookDetail(book)"><h3>{{ book.title }}</h3></a>

and I can get a object I saw it in console

  Get successful value returned in body [{…}]
    
    0: {_id: "5fc91e5aa700213eb8c52de0", title: "A Promised Land"

[{…}] is 0: {_id: "5fc91e5aa700213eb8c52de0", title: "A Promised Land" ....

but I want to display only this specific book on a page named bookdetail, instead of all books currently being shown.

Below is the bookdetail component:

   import { Component, OnInit } from '@angular/core';
    import { DataService } from '../data.service';
    
    @Component({
      selector: 'app-bookdetail',
      templateUrl: './bookdetail.component.html',
      styleUrls: ['./bookdetail.component.scss']
    })
    export class BookDetailComponent implements OnInit {
    
      h1Style: boolean = false;
      books: Object;
    
      constructor(private data: DataService) {}
    
      ngOnInit() {
        this.data.getBooks().subscribe(data=> {
          console.log({data})  //show data
          this.books = data
          //console.log(this.books);
      })
      }
    
    }

in bookdetail html

  <h1>Book-detail</h1>
    <div *ngIf="books" class="bookdetail-block">
      <div *ngFor="let bookdetail of books" class="bookdetail">
        <h1>{{bookdetail.title}}</h1>
        <p><img [src]="bookdetail.image" ></p>
        <p>{{bookdetail.author}}</p>
        <p>{{bookdetail.price}}</p>
        <p>{{bookdetail.isbn}}</p>
        <p>{{bookdetail.description}}</p>
    
    </div>
    </div>

How do I only display the selected book?

I suspect the issue lies within the bookdetail ngOnInit() function??

Answer №1

To implement the functionality in your "detail-component", you can subscribe to ActiveRouter.params and retrieve route information. You can use switchMap to fetch the parameter and then call dataService.getOneBookDetail(id). Once you have the response, assign it to a variable and display the variable.

book:any
constructor(private activatedRoute:ActivatedRoute,private dataService:DataService){}
ngOnInit() {
  this.route.paramMap.pipe(
    switchMap(params => {
      const ibs=params.get('isbn');
      return this.dataService.getOneBookDetail(ibs);
    }).subscribe(res=>{
      book=res;
    })
  );
}

Another approach is to pass data between routes, as demonstrated by Netanel Basal

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

Eliminate unnecessary components during the JSON to CSV conversion process

I have a JSON data set that looks like this: {"id":1,"name":"Sam","birthday":"12December","age":"15"}, {"id":2,"name":"Ash","birthday":"12January","age":"23"} After passing the data through the function: ConvertToCSV(data) I can extract id, name, birth ...

Struggling with Angular Fire and Firebase Emulators in Updating Documents

Following the update of Angular Fire and Firebase Emulators to their latest versions, we encountered an issue where updating a document is no longer functioning. Despite being able to create new documents without any complications, both .update() and set() ...

Unable to create a connection to the server using websockets

Currently, I am working on a MEAN stack application. The communication between the client and server is handled through a combination of HTTP requests and websockets. Everything operates smoothly when running the application on localhost. However, upon at ...

What is the process for converting language json files into different languages?

I'm currently using ngx-translate to localize an Angular app. With over 20 languages that need translation, I am in search of a tool that can efficiently translate the language json files. While I did come across a helpful website, it proved to be ti ...

Unraveling nested elements with the array map() method in Angular2 and Typescript: Fixing the issue of undefined property reference while mapping

Hey there! I'm currently working with Angular 4 and I have a piece of code that parses data from an API into a TypeScript array of rows. It's important to note that the code functions properly if elements like 'item.tceCampRun' and &apo ...

deleting a column in a two-dimensional array

I've been working on creating a class to remove a column from a 2D array, but I'm encountering some confusing errors. It seems like I might be missing something fundamental here. Any assistance would be greatly appreciated. public class ColumnRe ...

What is the best way to iterate over an associative array and display the contents as a list?

After successfully setting up my initial array, I have been struggling to loop through each row and display the three columns/elements in a tag. Here is the var_dump of my array: array(27) { [3]=> array(3) { ["id"]=> string(3) "295" ["title"]=gt ...

Extracting properties from an object in NodeJS: a step-by-step guide

I'm struggling to access a specific property within an object using a GET request in NodeJs (with express). Here is the object I am working with: const friends = [{ id: 1, name: "laura", country: "England", language ...

Try out NextJS API middleware by running tests with Jest

I have a middleware setup in my NextJS API route, located at /src/middleware/validateData/index.ts. It's used to validate request data using a schema. import { NextApiRequest, NextApiResponse } from 'next'; import schema from './schema ...

What is the best way to save geolocation coordinates in a Javascript array?

I am attempting to utilize HTML5 geolocation to determine a user's location and then store the latitude and longitude coordinates in an array for future use with Google Maps and SQL statements. However, when I attempt to add these coordinates to the a ...

The system encountered an issue: Unable to access the filter property of an undefined property

Here is my form code in TypeScript: this.editForm = this.fb.group({ 'dropoffs': this.fb.array(this.createDropOffFacility(data.dropoffs.filter(picks => picks.drop_facility !== ''))), }); createDropOffFacility(facilities) { ...

Assign specific classes to the rows and overall table by extracting information from the first row and first column of the table

My goal is to utilize jQuery in order to dynamically assign classes to the rows and columns of a table based on the classes of the first row and column. For instance: The current HTML code I have is as follows: <table class="numAlpha" border="1"> ...

What is the best way to authenticate an admin in the front-end using backend technologies like Node.js, Angular, and MongoDB?

Within the user model, there is a property named isAdmin with a default value of false. In MongoDB, I have manually created an admin account with the isAdmin property set to true. When logging in as an admin, the program verifies this and displays "admin ...

Implementing a conditional chaining function in TypeScript

I'm currently facing an issue while implementing a set of chained functions. interface IAdvancedCalculator { add(value: number): this; subtract(value: number): this; divideBy(value: number): this; multiplyBy(value: number): this; calculate( ...

Validation of time input using Angular Material within a ReactiveForm

Currently immersed in Angular 17 along with Material theme, I find myself faced with a scenario involving Reactive Forms housing two time-input fields. The array [minHour, maxHour] should represent a range of Hours, let's say [09:00 , 13:00]. HTML [ ...

Guide on comparing an object against an array and retrieving a specific output

If I were to create a data structure like this: const carObj = {"1234":"Corvette","4321":"Subaru","8891":"Volvo"}; And also have an array that contains the IDs: const myArray = [1234, 4321, 8891, ...

Guide on incorporating a range object into a VBA function to produce an array output

I'm running into an issue with my code where a procedure that generates cell ranges based on specific criteria is causing problems when I try to call a function that takes a cell range object as input and returns an array. The error message I keep rec ...

Querying MongoDB for nested fields

I'm trying to retrieve the "type" field but I can't seem to find the correct syntax. Can anyone help?https://i.sstatic.net/DZMcI.png ...

Merge objects based on specific property within an array of objects

Is there a way to merge objects based on one property and also add missing Days names in the output? Consider this example: var array = [ { "heure1": "14:00", "heure2": "17:00", "day&q ...

Manipulate elements within a PHP stdClass by selecting elements that contain a specific value

My stdClass object looks like this: object(stdClass)#2 (6) { [0]=> object(stdClass)#44 (2) { ["uid"]=> int(3232) ["type"]=> string(7) "sibling" } [1]=> object(stdClass)#43 (2) { ["uid"]=> int(32323) ["t ...