After successfully logging the user into my app, I want to redirect them imperatively to the portal page. However, when I use the router.navigate() function, a few things happen that are causing issues. First, the app redirects to /portal. Then, it immediately redirects again to /portal with Email Address and Password as query strings. Finally, it seems like the app "resets" in some way, forgetting that the user has already logged in, so it redirects back to the login page. What could be causing this problem?
All of this is happening within a form onSubmit event, triggered by this button:
<button type="submit" (click)="onSubmit(Form)">Sign in</button>
Here is the onSubmit code snippet:
public onSubmit(form: EmailForm): void {
this.apiLogin.LoginUser(form.EmailAddress, form.Password).subscribe(
(user: LoginUser) => {
if(user.UserToken == null) {
this.addValidationError("Invalid username and/or password.");
}
else {
this.appState.setUser(user);
}
},
(err) => {},
() => {
this.router.navigate(['/portal']);
}
);
}
Additionally, here is how my routes are set up:
const appRoutes: Routes = [
{ path: '', component: HomeComponent, pathMatch: 'full' },
{ path: 'portal', component: PortalComponent, canActivate: [AuthGuard] },
{ path: '**', component: PageNotFoundComponent }
];
Although not necessary, here is the AuthGuard service used on the portal route. Thanks to @Sasxa for assisting me in implementing this AuthGuard.
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private appState: ApplicationState, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let url: string = state.url;
return this.checkLogin(url);
}
checkLogin(url: string): boolean {
if (this.appState.User.UserToken) return true;
this.navToLogin(url);
return false;
}
private navToLogin(redirUrl: string) {
this.router.navigate(['/']);
}
} // end class