簡體   English   中英

Angular Auth Guard 沒有導航到新的 Route

[英]Angular Auth Guard is not navigating to new Route

我的 Auth Guard 在不登錄的情況下嘗試搜索 URL 時按預期工作。但是,登錄時,URL 中的導航不會改變,用戶也不會被路由到正確的頁面。 但是,它運行正確的登錄方法以重新路由到預期頁面,所以我不確定為什么不是,或者在使用 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;
    
  }
  
}

我的登錄方法。 注意其中的 console.log()。 它在使用 Auth Guard 時運行,證明它應該可以工作......

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)
      })
  }

我的 Getter 方法為 Auth Guard 返回一個布爾值......

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

我的懶加載路線...

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)
    }
  ];

更新

我也應該澄清一下。 如果我去掉 Routes 文件中的 Auth Guard,登錄方法會導航到正確的頁面。 它與Auth Guard有關。 添加如上所示的代碼會影響導航運行。

更新

這是我的 Auth 組件的路由文件,其中包含一個“/”路徑...

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 { }

更新

在 signIn 方法中,我嘗試在構造函數中注入一個 route:ActivatedRoute 並替換

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

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

它有時似乎有效*,但有時卻無效。 所以我不確定是什么原因造成的。 任何精通路由及其與 Auth Guard 關系的人,或者知道為什么會發生這種情況?

重定向后return false

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

它不是逐行執行。 將 return true 包裝到 else 塊中。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM