Angular: Automatically navigate to the parent page if the child parameter ID is missing

I currently have two separate modules with their own unique routing setups:

CarsModule

PassengersModule (Lazy Loaded)

Passenger is essentially a child of car and can be accessed through the following URL structure:

https://localhost/cars/12/passengers/1

Both CarsModule and PassengersModule have their routes clearly defined as shown below:

const routesCars: Routes = [
    {
        path: "cars/:id",
        canActivate: [AuthGuard],
        component: CarsContainerComponent,
        children: [
            {
                path: "",
                redirectTo: "dashboard",
                pathMatch: "full",
            },
            {
                path: "dashboard",
                component: CarsDashboardPageComponent,
            },
            {
                path: "passengers",
                loadChildren: () =>
                    import("./passengers/passengers.module").then(
                        (m) => m.PassengersModule
                    ),
            },
        ],
    },
];

const routesPassenger: Routes = [
    {
        path: "",
        redirectTo: ?????
    },
    {
        path: ":pid",
        component: PassengerDashboardContainerComponent,
        children: [
            {
                path: "",
                component: PassengerDashboardContainerComponent,
            },
        ],
    },
];

In cases where a user navigates to a passenger without specifying pid in the URL:

http://localhost/cars/12/passengers

I aim to automatically redirect that URL back to the parent Car URL:

http://localhost/cars/12

I initially attempted handling this scenario within an empty component loaded on the path: "", but it felt cumbersome. What would be the most efficient approach to achieve this?

Answer №1

One way to control the activation of a route is by using a guard.

PassengerRoute.service.ts

import { Injectable } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Injectable()
export class PassengerRouteGuard implements CanActivate {
  constructor(private route: ActivatedRoute, public router: Router) { }
  canActivate(): boolean {
    this.route.params.subscribe(params => {
      if (!params['pid']) {
        this.router.navigate(['/cars/']);
        return false;
      }
      return true;
    });
  }
}

PassengersModule.route.ts

import { PassengerRouteGuard} from './PassengerRoute.service';
const routesPassenger: Routes = [
{
    path: ":pid",
    canActivate: [PassengerRouteGuard],
    component: PassengerDashboardContainerComponent,
    children: [
        {
            path: "",
            component: PassengerDashboardContainerComponent,
        },
    ],
},
];

More information here

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

What is the method by which the Material-UI Button component determines the properties for the component that is passed to the `component` prop

Could someone please clarify how Material-UI enhances the properties of its Button component by incorporating the properties of a specific component if passed in the component attribute? interface MyLinkProps extends ButtonBaseProps { someRandomProp: str ...

The parameter type cannot be assigned to an array type of 'IAulasAdicionais[]'

I am facing a problem in my application that I need help solving. The issue lies within my code, and I have included some prints of the error below: Mock data: "AulasAdicionais": [ { "Periodo": "1", "Hora ...

Definitions for Typescript types that describe a custom hook responsible for fetching a specific part of the Redux state

I've created a custom hook called useReduxState to fetch a specific piece of state from Redux like so: const STATE_A = useReduxState("STATE_A"); Now, I'm running into issues when trying to integrate Typescript. These are the types I a ...

Leveraging cloud functions on Firebase for maximum efficiency

Question: Do you require a backend language when using Firebase Cloud Functions, or can TypeScript alone suffice for coding tasks like creating a matchmaking system? Response: There seems to be some uncertainty on the matter even from ChatGPT himself. Is ...

Developing a Customized Filtering Mechanism in Angular 8

I have some experience working in web development, but I am relatively new to Angular. My current project involves creating a simple filter for a table's column based on user input. However, I'm facing an issue where typing in a single letter fil ...

Neither Output nor EventEmitter are transmitting data

I am struggling to pass data from my child component to my parent component using the Output() and EventEmitter methods. Despite the fact that the emitter function in the child component is being called, it seems like no data is actually being sent through ...

What is the proper way to utilize a function in C# that integrates with a window form using TypeScript?

I am currently working on a code that is in c# and utilizes a web browser. My goal is to convert the existing JavaScript code to Angular 7 and Typescript. Below is the c# code and the corresponding JavaScript code used to access the c# function from JavaS ...

Photo captured by camera is not stored in photo gallery

I am currently working on a basic image upload form that allows users to take photos using their phone camera and upload them. However, I have noticed that the pictures taken this way are not being saved to the gallery. Is there something missing in the H ...

Exploring the power of Typescript functions within a traditional VueJS project

TL;DR: How can I import and use a typescript module into my plain js Vue-Components? I have a Vue 2 (not yet 3) project. In this specific project, I have made the decision to refactor some of the code logic into ES modules for improved testability and reu ...

Error: Trying to access a property that does not exist on an undefined object (retrieving 'kind

Currently, I am working on a project using angular-CLI. When I attempted to create a new module yesterday, an error popped up in the terminal saying Cannot read properties of undefined (reading 'kind') (only this error there wasn't an ...

Basic cordova application that transfers data from one page to another using typescript

Currently, I am developing an Apache Cordova application using TypeScript. However, I am facing a challenge in passing information from one HTML page to another using TypeScript. I would appreciate it if someone could guide me on the steps needed for nav ...

Highly Transferable Angular Modules for 'ng-cli'

I am managing a system with multiple Angular applications built using the ng-cli: FrontendLibs @company/ core/ src/ package.json index.ts main-app/ src/ package.json In this scenario, I have two Angular applications name ...

Implementation of a function in Typescript that can be defined with a

I am currently diving into the Typescript specification and I'm facing a challenge in creating a functional implementation for describable functions. https://www.typescriptlang.org/docs/handbook/2/functions.html The provided example lacks completene ...

obtaining the status of a checkbox in ionic2

Here is the scenario: I am managing a list of users. Additionally, I have a collection of items where each item contains an array of associated users. The display of the items list is as follows: <ion-list> <ion-item *ngFor="let item of it ...

Click event based on condition in Angular 2

Is it possible to implement a conditional click event in my application? <div class="trashIconDiv" (click)="if(idx > 0) {removeSelected(item.spId)}"> In the code snippet above, the removeSelected function is supposed to execute only when idx is ...

In Typescript, try/catch blocks do not capture return values

I am currently working on a function that performs database operations, with the implementation contained within a try/catch block. Here is an example: async function update({id, ...changes}): Promise<IUserResult> { try { //insert code here retu ...

What steps can I take to ensure TypeScript compiler approves of variance in calling generic handlers, such as those used in expressJS middleware?

disclaimer: I am a bit uncertain about variance in general... Here is the scenario I am facing: // index.ts import express from 'express'; import {Request, Response} from 'express'; const app = express(); app.use(handler); interface ...

Transforming a JavaScript Date object to a Java LocalDateTime

In my current project, I am facing a challenge while attempting to pass UTC time from a JavaScript front end to a Java backend. My initial approach involved utilizing the Date.toISOString() method and sending the generated object to the Java backend. Howev ...

Using lambdas in JSX attributes is not allowed because it can negatively impact rendering performance

I encountered an error when using the following code:- <FieldArray name="amenities" render={arrayHelpers => ( <div> {values.amenitieslist && values.amenitieslist.length > 0 ? ( val ...

Unlock the encrypted information in the blockchain

I've been working on encrypting and decrypting values using Node's built-in crypto module. I found a helpful tutorial that showed me how to encrypt the data, but it didn't provide any sample code for decryption. When I tried using code from ...