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

Intellisense in VSCode is failing to suggest subfolder exports

In my setup, I have a repository/module specifically designed to export TypeScript types into another project. Both of these projects are using TypeScript with ECMAScript modules. The relevant part of the tsconfig.json configuration is as follows: "ta ...

Utilizing Angular 9's inherent Ng directives to validate input components within child elements

In my current setup, I have a text control input component that serves as the input field for my form. This component is reused for various types of input data such as Name, Email, Password, etc. The component has been configured to accept properties like ...

Making changes to a single formControl in angular6 will cause the other formControl to be updated as

I have two select menus in my user interface with the same options. When I select an option in one menu, I want the other menu to display the same option, and vice versa. Currently, I am using the valueChanges method on the first formControl to update the ...

Angular 2: Embracing the Power of Hierarchical Selection

My goal is to create cascading selects where each option in a dropdown menu can lead to its own set of unique child options. This will result in a hierarchical structure of selectable items. To accomplish this, I have defined a class named fieldSelect tha ...

Using the index in Vue.js to locate a method within an HTML file

Currently, I am attempting to make use of the reference "index" located within <tr v-for="(note, index) in noteList" v-bind:key="index" in order to call shareToPublic(index). The method selectedID() allows for the selection of the ...

Retrieving specific information from the Model and returning it as a JSON response using annotations

I am interested in receiving a JSON response with additional annotations. Currently, my JSON response looks like: { "id": 1, "startDate": [ 1993, 12, 12 ], "endDate": [ 2018, 11, 22 ], "totalDistance": 255, "totalPrice": 211 } How ...

Definitions for TypeScript related to the restivus.d.ts file

If you're looking for the TypeScript definition I mentioned, you can find it here. I've been working with a Meteor package called restivus. When using it, you simply instantiate the constructor like this: var Api = new Restivus({ useDefaultA ...

DeActivation only occurs once per route

Having an issue with the CanDeActivate() function in Angular2. The problem arises when a user tries to leave a page while in edit mode, triggering a popup with Yes, No, and Cancel options. If the user clicks on Cancel, the popup closes. If they click on No ...

Ionic4: Troubleshooting the playback of audio files on a web-based application

Currently, my project involves using Ionic 4 in combination with Angular. I am facing a challenge where I need to play an audio file (mp3/wav) when an image is clicked. Despite working on this for a week, I have been unable to figure it out. Can anyone pr ...

Integrate attributes from several personalized hooks that utilize useQuery with secure data typing in React Query

I am currently facing a challenge where I have multiple custom hooks that return query results using useQuery. My goal is to combine the return values from these hooks into one object with the following structure: { data, isLoading, isFetching, isS ...

Exploring Facebook Graph API response with Angular 2 Mapping

I am using HTTP calls to access the Graph API in order to retrieve posts from a Facebook page. Here is the code snippet that fetches an array of posts: let url = 'https://graph.facebook.com/15087023444/posts?fields=likes.limit(0).summary(true),comme ...

What are the steps to integrate the TawkTo JS API into an Angular application?

I'm running into some challenges trying to implement the TawkTo JS API within my Angular application. Can anyone provide guidance on how to effectively integrate it? ...

Ensuring data validity in Angular 2 before enabling a checkbox

In my form, there is a checkbox for admins to edit user accounts. Each user object includes a boolean value isAdmin. I am trying to prevent users from editing their own account while still allowing them to view the values. However, no matter what I try, I ...

Issues with the ngModel data binding functionality

I'm currently working on the Tour of Heroes project and facing an issue with ngModel. It seems like hero.name is not being updated, or maybe it's just not reflecting in the view. Despite typing into the input field, the displayed name remains as ...

Unable to access member function of Typescript class

I recently started using typescript and encountered an issue while working on a problem. I initially created the following class: export class ModuleInfoContainer extends Array<ModuleInfo> { constructor() { super(); } search(id: number) { ...

The argument labeled as 'State' cannot be assigned to a parameter labeled as 'never'

I've recently delved into using TypeScript with React. I attempted to incorporate it with the React useReducer hook, but I hit a roadblock due to an unusual error. Below is my code snippet: export interface ContractObj { company: string; ...

Transitioning from angular 7 to the latest version 12

Upgrading from Angular 7 to 12 has presented a series of issues for me. The main problem seems to be with Angular Material. I am looking for a solution to this. ./src/app/material.module.ts:13:89-110 - Encounter Error: 'MatAutocompleteModule' ( ...

Can we verify if strings can serve as valid property names for interfaces?

Let's consider an interface presented below: interface User { id: string; name: string; age: number; } We also have a method defined as follows: function getUserValues(properties:string[]):void { Ajax.fetch("user", properties).then( ...

Is it possible to assign a string literal type as a key in TypeScript mappings?

Is it possible to map a string literal type as a key in a new type? I attempted this, but it did not work as expected. const obj = { type: "key", actions: { a() {}, b() {}, }, } as const; /* Map to { key: { a() {}, b() {}, } */ t ...

Angular 8 delivers an observable as a result following a series of asynchronous requests

I am working on a simple function that executes 3 asynchronous functions in sequence: fetchData() { this.fetchUsers('2') .pipe( flatMap((data: any) => { return this.fetchPosts(data.id); }), fl ...