JRobi17X
JRobi17X

Reputation: 67

Is there a way to switch two components in routing?

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);
    }

So currently my routing is working the following way: I can reach a driver's details with the following path: localhost:4200/driver-details/id

But, I would need the other way around, so like this: localhost:4200/id/driver-details

I tried to "switch" the order like this: {path: ':id/driver-details', component: DriverDetailsComponent}, but unfortunately that wasn't the solution.

enter image description here

Upvotes: 0

Views: 84

Answers (1)

Nico
Nico

Reputation: 316

You can do this by using child routes:

const routes: Routes = [
    {        
        path: 'drivers',
        component: DriverListComponent
    },
    {        
        path: 'driver',
        children: [
            {
                path: ':id',
                children: [
                    {
                        path: '', 
                        redirectTo: 'driver-details',  
                        pathMatch: 'full'
                    },
                    {
                        path: 'driver-details',
                        component: DriverDetailsComponent
                    }
                ]
            }
        ]    
    }
]

By calling 'localhost:4200/driver/6/driver-details', the 'DriverDetailsComponent' will be called.

You can find more information on these type of routes here.

Upvotes: 1

Related Questions