0

Here is my work.

I set up a guard to forward the request URI /admin to /login, you may refer /admin/admin.guard.ts for detail.

It works fine. However, when the request URI is /admin/abc, it does not work.

The following is the /admin/admin-routing.module.ts content:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AdminComponent } from './admin.component';
import { AdminGuard } from './admin.guard';
const routes: Routes = [
  {
    path: 'admin',
    canActivate: [AdminGuard],
    component: AdminComponent,
    children: [
      {
        path: '',
        redirectTo: 'admin',
        pathMatch: 'full'
      },
      {
        path: '**',
        redirectTo: 'admin',
        pathMatch: 'full'
      }
    ]
  }
];

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

How can I fix the problem?

2 Answers 2

1

Use absolute paths for the redirect:

const routes: Routes = [
{
  path: 'admin',
  canActivate: [AdminGuard],
  component: AdminComponent,
  children: [
    {
      path: '',
      redirectTo: '/admin',
      pathMatch: 'full'
    },
    {
      path: '**',
      redirectTo: '/admin',
      pathMatch: 'full'
    }
  ]
}
];

If you use relative paths there would be an infinite loop of redirects. From /admin/123 to /admin/admin to /admin/admin and so on.

Sign up to request clarification or add additional context in comments.

Comments

0

You may want to check the order in which you have registered your custom angular modules under imports in app.module.ts. Make sure the module that contains a route entry for { path: '**', ... } is listed at the end, after other modules.

For e.g in your case, keep adming AdminRoutingModule at the end in the app.module.ts:

@NgModule({
  declarations: [ ... ]
  imports: [
   // Angular in-built modules
   // Your custom modules
   AdminRoutingModule
  ],
  providers: [ ... ],
  entryComponents: [ ... ],
  bootstrap: [ AppComponent ]
})

** indicates the final option for url to be redicted when no matches found with exisiting routes registred with application. Also consider using absolute path in redirectTo property like /admin.

So I'm not sure if this will help with your problem, but worth giving it a try!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.