Angular App returns to Default(Home Component) on refresh

Viewed 371

My App is working fine so far beside that my router brings me back to the Default Route. For Example: I am on localhost:4000/Settings than refresh: and i land on localhost:4000 That happens on all sites.

Anybody has an idea why this happens ? btw. i didnt set a Default rout though.

This is my Routing Module:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { MediaComponent } from './media/media.component';
import { RegisterComponent } from './register/register.component';
import { AuthGuard } from './auth.guard';
import { SettingsComponent } from './settings/settings.component';
import { LoginComponent } from './login/login.component';


const routes: Routes = [
  {path: '', component: LoginComponent},
  {path: 'Register', component: RegisterComponent},
  {path: 'Home', component: HomeComponent, canActivate:[AuthGuard]},
  {path: 'Media', component: MediaComponent, canActivate:[AuthGuard]},
  {path: 'Settings', component: SettingsComponent, canActivate:[AuthGuard]}
];

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

AuthGuard:

canActivate(   
  route: ActivatedRouteSnapshot, 
  router: RouterStateSnapshot): Observable<boolean> {
  return this.afAuth.authState.pipe(
    take(1),
    map(user => !!user),
    tap(loggedIn => {
      if (!loggedIn) {
        console.log('Access Denied');
        window.alert('kein Zugang bitte Registrieren oder einlogen')
        this.router.navigate(['Login']);
      }
    })
  );
}

Index.html:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Luke's Page</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>

App.Component:

<app-navbar></app-navbar>
<router-outlet></router-outlet>
1 Answers

Try putting you default route last

const routes: Routes = [
  {path: 'Register', component: RegisterComponent},
  {path: 'Home', component: HomeComponent, canActivate:[AuthGuard]},
  {path: 'Media', component: MediaComponent, canActivate:[AuthGuard]},
  {path: 'Settings', component: SettingsComponent, canActivate:[AuthGuard]},
  {path: '', component: LoginComponent},
];

The router chooses the first one it matches to.

Related