Reputation: 97
So I dont want users to view some pages if they are not logged in. So I am using auth guard and if they try to access a path without being loged in they will be redirected to the login page.
Following is my 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;
}
}
Following is my 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 { }
So my problem is, When it try to access my signup page (/signup) I am being redirected to the login page and I am not able to figure out why. Following is my signup page:
@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);
});
}
}
Any help would be much appreciated. Thank you soo much.
Upvotes: 0
Views: 377
Reputation: 2164
The if (this.authService.isLoggedIn)
in the SignupComponent should be
if (this.authService.isLoggedIn())
--> note the ()
after isLoggedIn
otherwise you only check if there is a function called isLoggedIn
in the auth.service
Upvotes: 1