driver-details.component.ts
@Component({
selector: 'app-driver-details',
templateUrl: './driver-details.component.html',
styleUrls: ['./driver-details.component.css']
})
export class DriverDetailsComponent implements OnInit {
id!: number;
driver!: Driver;
constructor(private route: ActivatedRoute, private driverService: DriverService) { }
ngOnInit(): void {
this.id = this.route.snapshot.params["id"];
this.driver = new Driver();
this.driverService.getDriverById(this.id).subscribe(data =>{
this.driver = data;
})
}
app-routing.module.ts
const routes: Routes = [
{path: 'drivers', component: DriverListComponent},
{path: 'driver-details/:id', component: DriverDetailsComponent},
{path: '', redirectTo: 'drivers', pathMatch: 'full'}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
DriverController.java
@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("/api/v1/")
public class DriverController {
@Autowired
private DriverRepository driverRepository;
@GetMapping("/drivers")
public List<Driver> getAllDrivers(){
return driverRepository.findAll();
}
@GetMapping("/drivers/{id}")
public ResponseEntity<Driver> getDriverById(@PathVariable Long id) {
Driver driver = driverRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Driver not exist with id :" + id));
return ResponseEntity.ok(driver);
}
Currently, my routing system allows me to access a driver's details using the path: localhost:4200/driver-details/id
However, I need to reverse the order so that it becomes: localhost:4200/id/driver-details
I attempted to modify the path like this: {path: ':id/driver-details', component: DriverDetailsComponent}, but unfortunately, it did not work as expected.