I'm having trouble getting a redirect in my routing module working, and adding an AuthGuard in CanActivate complicates it even further. Here is a simplified router:
const routes: Routes = [
{
path: 'login',
component: LoginComponent,
},
{
path: 'home',
component: HomeComponent,
},
{
path: 'secret',
component: SecretComponent,
canActivate: [ AuthGuard ]
},
{ path: '', redirectTo: '/home', pathMatch: 'full' },
];
With this current setup, I get some strange behavior. Every route is considered a child of the path: ''
route, so going to '' brings you to '/home'. If I refresh the page, I go to '/home/home'. This goes for login as well - navigation to '/login' will actually take you to '/login/home'. If you refresh any of these pages after the extra '/home' has been tacked onto the end, it causes the page to error out.
The authguard is just another complication, what with it navigating the user around based on authentication status.
Things I have tried:
- Removing the authguard
- Changing the order of the path declarations
- Having only a single path + blank path redirecting to it
pathMatch: 'prefix'
- Using '**' as the redirect route
- Upgrading to Angular 12
- Deleting / recreating the entire routing module
I'm comparing this to some functioning production projects, example tutorials, etc. Everything seems to be in place. Not sure what's going wrong.
NOTE: The project is in Angular 9 for some reason I just noticed even though I just made it recently. It might be worth updating early on, but I don't think that's relevant to the issue.
UPDATE: I updated to Angular 12, it had no effect. And actually I noticed that NO routes are working. So navigating to /secret or /login does nothing.
Here is a new config:
const routes: Routes = [
{
path: 'login',
component: LoginComponent,
},
{
path: '',
component: HomeComponent,
},
{
path: 'secret',
component: SecretComponent,
canActivate: [ AuthGuard ]
},
];
With that layout, I can navigate to '' and I see the home component. If I navigate to '/login', I see the home component. If I click a button that calls this.router.navigate(['/', 'login']);
the page is now at '/login' and shows the login component. If I refresh that page, I then see the home component while still on the same '/login' route that was just showing the login component before. I am very confused.
Whenever I navigate to a route, for example "localhost:4200/login" it will change the URL to "localhost:4200/login/". If I refresh with that url or renavigate to that url with the slash at the end, I see a number of 404 errors in the console and nothing from the app template loads in. (Such as the footer component.)
UPDATE 2: I created a new Angular project and have basically the exact same route setup and everything is functioning as expected. I don't know if just recreating everything is the correct next step, but it's looking awfully tempting.