简体   繁体   中英

Angular Auth Guard is not navigating to new Route

My Auth Guard is working as intended in regards to attempting to search a URL without logging in. However, when signing in, the navigation in the URL does not change and the user is not routed to the correct page. It is*, however, running the correct sign in method to reroute to the intended page, so I'm not sure why it is not or if there's some sort of underlying rule I'm missing when using an Auth Guard. I am also using a lazy loaded home page, in case that has something to do with it...

My Auth Guard...

import { Injectable } from '@angular/core';
import { CanLoad, Route, Router, UrlSegment } from '@angular/router';

import { Observable } from 'rxjs';

import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanLoad {
  constructor(
    private authService: AuthService, 
    private router: Router
  ) {}

  canLoad(route: Route, segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean  {
    if (this.authService.isLoggedIn !== true) {
      this.router.navigateByUrl('/')
    }
    return true;
    
  }
  
}

My Sign In method. Notice the console.log() within it. It runs when using the Auth Guard, proving that it should work...

signIn(email: string, password: string) {
    return this.afAuth.signInWithEmailAndPassword(email, password)
      .then((result) => {
        this.ngZone.run(() => {
          this.isLoggedIn$.next(true);
          console.log('Sign in method...');
          this.router.navigateByUrl('/home');
        });
        this.SetUserData(result.user);
      }).catch((error) => {
        window.alert(error.message)
      })
  }

My Getter Method to return a boolean for the Auth Guard...

get isLoggedIn(): boolean {
    const user = JSON.parse(localStorage.getItem('user'));
    return (user !== null) ? true : false;
  }

My Lazy Loaded Routes...

const routes: Routes = [
    {
      path: 'home', 
      canLoad: [AuthGuard], 
      loadChildren: () => 
        import('./home/home.module').then(m => m.HomeModule)
    }, 
    {
        path: 'onTheirWay', 
        canLoad: [AuthGuard], 
        loadChildren: () => 
            import('./on-their-way/on-their-way.module').then(m => m.OnTheirWayModule)
    }, 
    {
        path: 'preorders', 
        canLoad: [AuthGuard], 
        loadChildren: () => 
            import('./preorders/preorders.module').then(m => m.PreordersModule)
    }
  ];

UPDATE

I should also clarify. If I take away the Auth Guard in the Routes file, the sign in method navigates to the proper page as it should. It has something to do with the Auth Guard. Adding the code as shown above is affecting the navigation from running.

UPDATE

Here is my routes file for my Auth components which includes a "/" path...

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { SigninComponent } from './signin/signin.component';
import { SignoutComponent } from './signout/signout.component';
import { SignupComponent } from './signup/signup.component';

const routes: Routes = [
  { path: 'signout', component: SignoutComponent }, 
  { path: 'signup', component: SignupComponent }, 
  { path: '', component: SigninComponent }
];

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

UPDATE

In the signIn method, I tried injecting a route:ActivatedRoute in the constructor and replacing the

this.router.navigateByUrl('/home'); 

with

this.router.navigate(['/home'], { relativeTo: this.route });

It seems to work sometimes*, but other times it doesn't. So I'm not sure what's causing this. Anyone savvy with routing and its relationship with Auth Guard or know why this is happening?

Do a return false after your redirect.

 canLoad(route: Route, segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean  {
    if (this.authService.isLoggedIn !== true) {
      this.router.navigateByUrl('/');
      return false; // <-----------------------
    }
    return true;
    
  }

it is not line by line execution. Wrap return true into else block.

canLoad(route: Route, segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean  {
    if (this.authService.isLoggedIn !== true) {
      this.router.navigateByUrl('/')
    } else {
      return true;
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM