Is it possible to interchange the positions of two components in a routing system?

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.

https://i.stack.imgur.com/4MUku.png

Answer №1

If you want to achieve this, you can utilize 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
                    }
                ]
            }
        ]    
    }
]

When accessing 'localhost:4200/driver/6/driver-details', the 'DriverDetailsComponent' will be displayed.

For more detailed information about these types of routes, check out this article.

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

Adjusting the timeout for a particular operation according to its unique identifier

I am looking for a solution to call a method that posts an answer after an input change in my Angular project. I want to reset the timeout if another input change occurs to avoid multiple posts. Is there a smart way to achieve this? My project involves po ...

What are some examples of utilizing paths within the tsconfig.json file?

Exploring the concept of path-mapping within the tsconfig.json file led me to the idea of utilizing it to streamline cumbersome path references: The project layout is unconventional due to its placement in a mono-repository that houses various projects an ...

Is there a way to access the value of a public variable within the @input decorator of a function type?

I am working on a dropdown component that utilizes the @Input decorator to define a function with arguments, returning a boolean value. dropdown-abstract.component.ts @Input() public itemDisabled: (itemArgs: { dataItem: any; index: number }) => boo ...

Mastering the art of utilizing Angular Material's custom-palette colors for maximum impact. Unle

I have implemented a custom material-color palette where I defined the primary and accent palettes with specific shades as shown below: $my-app-primary: mat-palette($md-lightprimary ,500,900,A700 ); $my-app-accent: mat-palette($md-lightaccent, 500,900 ...

Unable to access responsibility data in HTML from this.project.responsibility.Responsibility

Having trouble displaying the responsibility in the project? Check out the JSON below. I'm having difficulty accessing this.project.responsibility.Responsibility in HTML. Any help would be much appreciated. I've tried various methods to access it ...

Angular2 date input field unable to restrict minimum and maximum dates

Having trouble with dynamic min and max attributes not being recognized in ionic2 when using the 'datetime-local' type. <ion-input value="" type="datetime-local" [formControl]="expdate" [attr.min]="mindate" [attr.max]="maxdate"></ion-in ...

How do I add a new module to an existing one using Angular-CLI?

After generating modules: $ ng generate module myTestModule installing module create src/app/my-test-module/my-test-module.module.ts $ ng generate module myTestModule2 installing module create src/app/my-test-module2/my-test-module2.module.ts I ha ...

Angular throws a NullInjectorError when a unit test fails due to issues with dependency

As a newcomer to Angular, I am struggling to grasp the concept of Dependency Injection (DI) and how it functions. My current challenge involves trying to pass a unit test successfully. Below is the code for the test; import { TestBed } from '@angula ...

Generate gzipped files using Angular CLI

I am attempting to populate a dist folder with the standard files along with their .gz versions. To achieve this, I used ng eject to obtain the webpack.config.js file in order to integrate the compression plugin from https://github.com/webpack-contrib/comp ...

Struggling to figure out webhooks with Stripe

I have encountered a strange issue while using Stripe webhooks to process payments on my website. When I set the currency to USD, it prompts me to provide an address outside of India, which is expected. However, when I change the currency to INR, the addre ...

Ways to verify if a value corresponds to a particular data type

Is there a more elegant way for TypeScript to check if a value matches a specific type without actually invoking it, instead of the method described below? Consider the following example: import { OdbEventProcessorFunc } from "./OdbEventProcessor&quo ...

Error: You're attempting to read content that has already been accessed

Encountered the following error message: sp-webpart-workbench-assembly_en-us_b854c4b93cc10a271230fd4a9e7b2b9b.js:661 Uncaught (in promise) TypeError: Already read at t.e.json (sp-webpart-workbench-assembly_en-us_b854c4b93cc10a271230fd4a9e7b2b9b. ...

Switching Angular fxLayout from row to column based on a conditional statementHere is an explanation of how to

Visit this link for more information Is there a way to set direction based on a specific value? <div if(value) fxLayout='row' else fxLayout='column'> ...

What are the steps for utilizing @JoinColumn in a OneToOne mapping within hibernate?

After encountering various questions about @JoinColumn, I thought I understood the concept well. However, a new situation has arisen that has left me puzzled. Consider a OneToOne Unidirectional mapping with the following annotations in the parent class: C ...

Master the Art of Scrolling Lists in Ionic 2

I am currently using Ionic2 for my project. One of the challenges I'm facing is scrolling to the top of a list when a specific event, called messageSend, occurs. Let me show you the code for this: <ion-content padding class="messages-page-conten ...

Combining namespaces in Typescript declaration files

Currently, I am attempting to combine namespaces from d.ts files. For example, when I attempt to merge namespaces in a single file, everything works as expected. declare namespace tst { export interface info { info1: number; } var a: ...

Interfaces in Typescript

In my Angular 2 project, I am working on creating an interface for a complex object. Here is the code snippet of the object: // Defining the render state object this.aRenderState = { model: "", colour: false, showWireframe: false, showGrid: true, ...

Having issues with Bootstrap customization in an Angular 7 project

I am currently working on customizing a Bootstrap 4 theme within an Angular 7 project. After installing Bootstrap, I updated my angular .json file to include the following: "styles": [ "./node_modules/@angular/material/prebuilt-themes/de ...

The Angular component fails to retrieve data from a subscribed service when the data is being fetched from the sessionStorage

Within my Angular application, there exists a service that handles incoming objects by adding them to a list of objects, then saving the updated array to sessionStorage. This service also sends the updated list to another application that is subscribed to ...

Is it possible to change the value of a react-final-form Field component using the onSelect function?

I am currently working on a React application using TypeScript and incorporating the Google Places and Geocoder APIs through various React libraries such as "react-places-autocomplete": "^7.2.1" and "react-final-form": "^6.3.0". The issue I'm facing ...