簡體   English   中英

Angular auth guard 被應用在錯誤的路由上

[英]Angular auth guard being applied on wrong route

所以我不希望用戶在未登錄的情況下查看某些頁面。所以我正在使用身份驗證保護,如果他們嘗試在未登錄的情況下訪問路徑,他們將被重定向到登錄頁面。

以下是我的auth.guard.ts

@Injectable({
    providedIn: 'root'
})
export class NeedAuthGuard implements CanActivate {

  constructor(private authService: AuthService, private router: Router) {
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {


    if (this.authService.isLoggedIn()) {
      return true;
    }
    console.log('about to redirect to login -- inside auth guard');
    this.router.navigate(['/login']);

    return false;
  }

}

以下是我的app-routing.module.ts

const routes: Routes = [
 {
   path: '', component: SiteLayoutComponent,
   children: [
    { path: '', redirectTo: '/home', pathMatch: 'full' },
    { path: 'home', component: LandingPageComponent},
    { path: 'pricing', component: PricingComponent},
    { path: 'signup', component: SignupComponent},
    { path: 'login', component: LoginComponent},
   ]
 },
 {
  path: '', component: AppLayoutComponent,
  children: [
    { path: 'dashboard', component: DashboardComponent, canActivate: [NeedAuthGuard]} --> Only applied to dashboard
  ]
 }
];


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

所以我的問題是,當它嘗試訪問我的注冊頁面 (/signup) 時,我被重定向到登錄頁面,我無法弄清楚原因。 以下是我的注冊頁面:

@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.css']
})
export class SignupComponent implements OnInit {
  user: User;

  constructor(private authService: AuthService, private apiService: ApiService, private router: Router) {
    this.user = new User();
  }

  ngOnInit() {
   if (this.authService.isLoggedIn) {
      this.router.navigateByUrl('/dashboard');
   }
  }

  signup() {
    console.log('signup button clicked', this.user.email,  this.user.fullname, this.user.password);
    this.apiService.signup(this.user.email, this.user.fullname, this.user.password)
     .subscribe( response => {
        if(response.token) {
          this.authService.saveToken(response.token);
          console.log('signup - token saved');
          this.router.navigateByUrl('/dashboard');
        }
     }, response => {
          console.log(response.error.message);
     });
  }

}

任何幫助將非常感激。 非常感謝你。

SignupComponent 中的if (this.authService.isLoggedIn)應該是

if (this.authService.isLoggedIn()) --> 注意 isLoggedIn 后面的()

否則你只檢查 auth.service 中是否有一個名為isLoggedIn的 function

暫無
暫無

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

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