"Exploring the process of retrieving URL parameters within an activated link using Angular 7 and executing a REST API call from a service

My aim is to retrieve data by utilizing the id field through Get parameters. Below is the URL code in my HTML that redirects to a specific page without triggering the service to fetch the REST API.

  <a [routerLink]="['/usedCars/detail', lists.id]" class="btn btn-danger">Read more...</a>

Here is the function in my service.ts file where I have imported { HttpClient, HttpErrorResponse } from '@angular/common/http';

getcarDetail(id:string){
    return this.http.get<Autocardetail>(this.ServerUrl + 'autocardetail/'+id).pipe(
      catchError(this.handleError)
    );
  }

In my component.ts file, you will find the implementation of calling the service within the ngOnInit function.

import { Component, OnInit } from '@angular/core';

import { Router, ActivatedRoute, ParamMap} from '@angular/router';
import { Autocardetail } from '../autocardetail';
import { AutopostService } from '../autopost.service';

import { Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';

@Component({
  selector: 'app-autopostdetail',
  templateUrl: './autopostdetail.component.html',
  styleUrls: ['./autopostdetail.component.css']
})
export class AutopostdetailComponent implements OnInit {
  detail$: Observable<Autocardetail>;
  constructor(
        private route: ActivatedRoute,
        private router: Router,
        private autopostService: AutopostService
      ) {}

  ngOnInit() {
    this.detail$ = this.route.paramMap.pipe(
      switchMap((params: ParamMap) => {
        return this.autopostService.getcarDetail(params.get('id'))
    })
    );
  }
}

Furthermore, here is my class file structure:

export class Autocardetail {
  id: string;
  car_name: string;
  car_model: string;
  car_built: string;
  car_manufac_year: string;
}

This example from Postman demonstrates how a response looks like:

{
    "car_id": "0",
    "car_name": "Nissan",
    "car_model": "Sunny",
    "car_built": "Nissan inc",
    "car_manufac_year": "2019",
    "usedcarimages": [
        "0_Nissan-1.jpg",
        "0_Nissan-2.jpg"
    ]
}

You can refer to the following website for more information:

Answer №1

In the code you provided, the only potential issue I see is with the use of swtichMap().

As it stands-

switchMap((params: ParamMap) =>
  this.autopostService.getcarDetail(params.get('id'))
)

The line containing

this.autopostService.getcarDetail(params.get('id'))
should either be on the same line as swtichMap() if using an arrow function, or include an explicit return statement if breaking the line.

Correct ways to write it-

switchMap((params: ParamMap) => {
  return this.autopostService.getcarDetail(params.get('id'))
})

or

switchMap((params: ParamMap) => this.autopostService.getcarDetail(params.get('id')))

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

Determine the number of entries in a JSON object

I am encountering an issue while trying to calculate the number of records in a JSON object, as I am getting an incorrect count. Snippet var jsonObject = {"d":"[{\"Country\":\"\",\"CountryCo ...

Converting API data in Angular using rxjs

Hey there, I received this response from an API: { "records":[ { "id":1, "motivazione":"", "autorizzazione":false, } ] } Can anyone help me transform it to loo ...

One thing to note is that eloquent eager loading does not fetch associated model information

In my Laravel project, I am working with two Eloquent Models, namely Set and Card, which have a one-to-many relationship between them. This means that a Set can have many Cards, and each Card belongs to a Set. When attempting to retrieve the data using El ...

What is the best approach to prevent the occurrence of two instances of | async in this particular scenario (version 4.0

Is there a way to achieve the desired outcome in this component without using .subscribe()? I attempted to implement *ngIf="user$ | async as user" but encountered difficulties with it. What is the best approach to create a local variable using user$ | asy ...

having trouble with displaying the results on the webpage

I am facing an issue while trying to display the data fetched from the database: {"results": ["USA", "Canada"]} {"message":"Could not find any countries."} //else An error was encountered in the console: Uncaught TypeError: Cannot read property 'l ...

Deciphering the TypeScript type in question - tips and tricks

One of my abstract classes includes a static property with various properties, where default is consistently named while the others may have random names. public static data = { default: { //only this one always have 'dafault' name na ...

Union types can be used to constrain generic type parameters in Typescript

I'm working on a function uniqueIds(first: any[], second: any[]): number[] { let prop = first[0] instanceof Owner ? "OwnerId" : "BankId"; return _.unique( _.map( first, o => ...

modification of class into hooks, receiving error message 'then' property is not found in type '(dispatch: any) => Promise<void>'

As a newcomer to React hooks, I have been converting code from class components to hooks. However, I am encountering an error message when trying to use 'then' in hooks that says 'Property 'then' does not exist on type '(dispa ...

ngx-bootstrap: Typeahead, receiving an unexpected error with Observable

Encountering an error whenever more than 3 characters are typed into the input box. Error message: TypeError: You provided an invalid object where a stream was expected. Acceptable inputs include Observable, Promise, Array, or Iterable. .html file : < ...

What is the best way to deserialize nested JSON data with Spring RestTemplate?

After following the guide on consuming RESTful Web Services from the Spring website, I realized it did not cover the topic of deserializing nested objects. How would one go about deserializing the location entry in the provided sample? ...

Encountering a problem with serializing data.Json, unable to dump the data

import json data={"name":"John","age":30,"cars": [{ "name":"Ford", "models":["Fiesta", "Focus", "Mustang" ] },{ "name":"BMW", "models":[ "320", "X3", "X5"] },{ "name":"Fiat", "models":[ "500", "Panda" ] }]} with open('newjson','w') as ...

Tips for setting discrete mapper style in cytoscapejs?

Currently, I am defining the style of cytoscape.js through CSS and converting it to JSON format using this resource. My goal is to implement a discrete mapper for styling. It's similar to the scenario discussed in How to use a descreteMapper like on c ...

What is the best way to customize the appearance of a mat-checkbox in Angular using Angular Material?

Is there a way to customize the appearance of a mat-checkbox that actually works? I've tried various solutions without success. I attempted to disable view encapsulation and use classes like mdc-checkbox__background, but nothing changed. Even applyin ...

Transform a string into a JSON entity

Can JavaScript be used to convert a string such as this: "Product : Bike , 2005 : $12000,2006 : $13000,2007 : $14000,2008 : $15000" into a JSON object like the one below: { "Product":"Bike", "2005" : $12000, "2006" : $13000, "2007" : $14 ...

Converting a JSON array of key-value pairs to a Java HashMap using the Jackson JSON library

Currently, I am delving into my first Java Json parser library which happens to be Jackson JSON. I'm in the process of converting a List of ID/NOTE into a HashMap list as a Java Object. The structure of my Json input appears as follows: var basketL ...

Creating a TypeScript type or interface that represents an object with one of many keys or simply a string

I am tasked with creating an interface that can either be a string or an object with one of three specific keys. The function I have takes care of different errors and returns the appropriate message: export const determineError = (error: ServerAlerts): ...

Is it possible to retrieve messages from a service bus using an Angular app without relying on SignalR?

In our app, we are looking to post messages from our backend to an azure service bus in order to avoid waiting for a long process. Is it possible to do this directly from the front end, or do we need to implement a signalR solution with additional steps on ...

Looking for a solution to the TypeScript & Mantine issue of DateValue not being assignable?

The required project dependencies for this task are outlined below: "dependencies": { "@mantine/core": "^7.6.2", "@mantine/dates": "^7.6.2", "@mantine/form": "^7.6.2", &q ...

Instructions for displaying HTML content only when data is received from the server side

Using angular 4, I have implemented a div in my HTML to display a message when data is not found. However, the issue I am facing is that this div is shown even while the data is being fetched and has not been displayed yet. Ideally, I only want this div to ...

ExpressJs res.json throwing error - Headers cannot be set after they have already been sent

In my current project using ExpressJS, I have a specific route set up like this: router.route('/monitor') .all(function (req, res, next) { next(); }).get(monitor.monitorServers); There is also a controller named 'monitor' which co ...