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: