1
votes

I'm trying to cancel the initial path e.g.: localhost:4200/ should return an error view. Instead I want my home page to be accesible only if you navigate to something like localhost:4200/tag1/tag2.

I should be able to capture the url given and set it as home page. I have tried to do this in app-routing module but I get nothing loaded or errors saying the segments don't 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 { }
1

1 Answers

1
votes

You have some errors in your routing module.

  • First: tag1 and tag2 are variables. But you used as string in routes. It should be:
path: `${tag1}/${tag2}`
  • Second: you don't need to get url params directly in routing module. Instead, you can do like the belowing:
const routes: Routes = [
  { 
    path: '/:tag1/:tag2',
    loadChildren: () => import('../auth/auth.module').then(m => m.AuthModule) 
  },
  { 
    path: '',
    component: errorComponent    
  },
];

Then in your AuthPageComponent you can get tag1 and tag2 like the following:

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 more info, please refer to official doc: Route Parameters