角度身份验证保护应用于错误的路由

时间:2019-11-14 08:27:19

标签: angular typescript

因此,我不希望用户未登录就查看某些页面。因此,我使用的是auth Guard,如果他们尝试访问未登录的路径,则会将他们重定向到登录页面。

以下是我的 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);
     });
  }

}

任何帮助将不胜感激。太谢谢你了。

1 个答案:

答案 0 :(得分:1)

SignupComponent中的if (this.authService.isLoggedIn)应该是

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

否则,您仅检查auth.service中是否有名为isLoggedIn的函数