When the angular app loads, it should show the login component and then be navigated to the App Component on successful login.
The code follows,
app.module.ts
bootstrap: [LoginComponent]
app-routing.module.ts
const routes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'home', component: AddUserComponent, canActivate: [AuthGuard] }
}
AuthGuard
export class AuthGuard implements CanActivate {
constructor(private router: Router, private authService: AuthService) { }
canActivate(route, state: RouterStateSnapshot)
{
this.authService.isLoggedIn.subscribe(data => {
if (data)
this.router.navigate(['/home'])
this.router.navigate(['/login'], { queryParams:{ returnUrl: state.url }})
return false;
});
return true;
}
}
AuthService
export class AuthService {
constructor(private httpClient: HttpClient) { }
private _loggedIn = new BehaviorSubject<boolean>(false);
isLoggedIn = this._loggedIn.asObservable()
login() : Observable<boolean>
{
this._loggedIn.next(true);
return this.isLoggedIn
}
}
But after login, it is not navigating to the Home Component and it always stays in the Login Component and the login page loads again?
AuthGuard?ERROR Error: The selector "app-root" did not match any elements