Cancel the starting path in Angular 9 and initiate a redirection

I am attempting to change the initial path such as localhost:4200/ so that it displays an error view instead of the home page. I want the home page to only be accessible if you navigate to something like localhost:4200/tag1/tag2.

I need to be able to capture the given URL and set it as the home page. I have tried to implement this in the app-routing module, but nothing is loading or I receive errors stating that the segments do not exist.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {AppRoutes} from '../shared/globals/app-routes';
import {errorComponent} from '../errorComponent.ts'

export const tag1 = document.location.pathname.split('/')[1];
export const tag2 = document.location.pathname.split('/')[2];

const routes: Routes = [
  { path: 'tag1/tag2',
    loadChildren: () => import('../auth/auth.module').then(m => m.AuthModule) },
    { path: '',
    component: errorComponent    },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Answer №1

Your routing module has some issues that need to be fixed.

  • First: The variables tag1 and tag2 should not be used as strings in your routes. They are meant to be variables, so the correct format is:
path: `${tag1}/${tag2}`
  • Second: Avoid directly getting URL parameters in the routing module. Instead, structure your code as follows:
const routes: Routes = [
  { 
    path: '/:tag1/:tag2',
    loadChildren: () => import('../auth/auth.module').then(m => m.AuthModule) 
  },
  { 
    path: '',
    component: errorComponent    
  },
];

In your AuthPageComponent, you can retrieve tag1 and tag2 using the following method:

import { ActivatedRoute }  from "@angular/router";

constructor(
  private route: ActivatedRoute
) {
}

ngOnInit() {
  this.route.params.subscribe((params: { tag1: string, tag2: string }) => {
    console.log("tag1", params.tag1);
    console.log("tag2", params.tag2);
  })
}

For additional information, please consult the official documentation: Route Parameters

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

When a dialog box is displayed, a scrollbar will automatically appear

I've encountered a strange issue while working with Angular dialogs: A vertical scrollbar unexpectedly appears, even though I've set the dialog to have a fixed width. component.ts const dialog = this.dialog.open(DialogComponent, { width: ...

How can I establish default values for 2 to 3 options in a Dropdownlist?

Is there a way to set two values as default in a dropdown list, and when the page is refreshed, the last two selected values are retained as defaults? Thanks in advance! Visit this link for more information ...

Retrieving the data from a observable

Hello, I am currently learning Typescript/Angular, so please excuse me if this question has already been asked (I couldn't find it) or if it has a simple solution :) My goal is to have a timer displayed on my webpage. I have implemented it in my comp ...

Divide a list Observable into two parts

In my code, I have an Observable called 'allItems$' which fetches an array of Items. The Items[] array looks something like this: [false, false, true, false] My goal is to split the 'allItems$' Observable into two separate Observables ...

Can you explain NodeSource in simple terms, and what purpose does it serve?

Not too long ago, I delved into researching how to effectively host a MEAN stack web application on AWS. During my quest for knowledge, I stumbled upon a tutorial that caught my eye. The one I ended up following can be found at https://www.youtube.com/wat ...

Inscribe latitude from marker onto input field

Currently, I am working on a feature where markers are added to Google Maps API v3 by clicking on the map. Each marker then displays its coordinates in an info window. However, I am facing an issue with picking up the latitude and longitude values and inse ...

Achieving www prefix enforcement for loading js file

I am facing an issue with the script on my website, which is built using OpenCart. The problem arises when accessing the site with a www prefix - the JavaScript file fails to load. However, when accessed without the www prefix (e.g. example.com), everyth ...

Executing the collection.find() function triggers an internal server issue and eventually leads to a timeout error

My ExpressJS backend was running smoothly with hardcoded data, but when I integrated MongoDB into the system, my requests for data started timing out. I added a record to a collection using the command prompt: > db stackmailer > db.sites.find() { ...

What is the best way to apply a jQuery function to multiple div elements simultaneously?

I am looking to implement a show/hide feature for a <div> using JavaScript and DOM properties. The idea is to use JavaScript's onclick() function with two buttons, show and hide, each in their respective <div>. Here is how it would ideall ...

ASP.Net - Unexpected JSON Format Error

As I work on my ASP.Net web application, I am encountering an issue with binding data from a database to a Google Combo chart via a Web Service class. While I can successfully bind the data to a grid view, attempting to bind it to the chart results in the ...

Obtain the Unprocessed Product Details with the Shopify-Buy Software Development Kit

I want to create an e-commerce web application using ES6, react, react-redux, and your js-buy-sdk API. When fetching products from Shopify and storing them in the store, I noticed that I only have limited data about a product such as: { attrs, shopClient, ...

React - Anticipated an assignment or invocation of a function

Recently starting my journey with reactjs and encountered a small issue. A pesky error keeps popping up saying: Expect an assignment or function call. It's related to the User function, however, I do call that function when creating a new object. Any ...

Attempting to grasp the concept of Typescript generics

I have a function defined as follows: interface ExtraModels extends Model { unknown: string } const write = async (data: ExtraModels[]) => { console.log(data[0].unknown) } This function is currently working. However, I want to modify it to: cons ...

What is the best way to incorporate multiple pages and export them in an angular2 project?

Having some issues with my code. Can anyone lend a hand? import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: `page1.html` }) @Component({ selector: 'my-app2', templateUrl: `page2.html` ...

Click event dynamically bound to list items

I have a web application built with Durandal and Knockout. Here is the HTML code snippet: <ul id="header"> </ul> In a JavaScript function, I am dynamically adding a list item as follows: $("#header).append('<li id="btn"><a hre ...

Is there a way for us to determine the time at which the user last took a screenshot or photo?

I am currently developing a website using Django and I have a unique requirement. I need to access the last image that a user has taken on their phone, without the image being shared by anyone else. The photo must be captured by the user's device itse ...

Having trouble with Ajax and facebox integration issues?

My website utilizes ajax jquery and facebox for interactive features. You can check out a demo here. The div with the ID "#content" contains links to other pages that open successfully using facebox. However, when I reload the content of this div using aj ...

Beginner's Guide: Building your debut JavaScript/TypeScript library on GitHub and npm

I am looking to develop a simple JavaScript/TypeScript library focused on color conversion. Some of the functions and types I aim to export include: export type HEX = string; export type RGB = { r: number; g: number; b: number }; export type RGBA = { r: n ...

I am interested in incorporating the ability to select and scroll the window without needing to interact with the scroll bar by

Imagine a visitor wanting to highlight all the information on a webpage. They choose to start dragging their cursor towards the bottom of the window. How can we enable the webpage to smoothly scroll down as they do this? ...

How to prevent click events and still enable scrolling within a DIV using CSS/JS

Basically, I am looking to enable scrolling within a DIV while also disabling click events. Any suggestions on how this can be achieved? Appreciate any help! ...