Reputation: 582
I have two components which are DashboardComponent and LoginComponent. when user hits my website url i.e http://localhost:4200 I have to render LoginComponent if user hasn't logedIn already. If user has logged in already, I have to render Dashboard component in the same route i.e http://localhost:4200
this.router.navigate(['login']);
Using this will require another route (/login). But I have to switch the components based on the logged in condition in the same route just as like facebook,instagram. how to achieve this in angular?
Update This is my router config
const routes: Routes = [
{path: '', component: DashboardComponent}
];
Upvotes: 0
Views: 120
Reputation: 582
Somehow i have found the work around. But im not sure if it is correct approach!
in DashboardComponent.html
<app-login *ngIf="!loginService.isUserLoggedIn()"></app-login>
<p *ngIf="loginService.isUserLoggedIn()">dashboard works!
<button (click)="loginService.logOut()" class="btn btn-danger">logout</button>
</p>
Created LoginService
export class LoginService {
constructor() { }
public authenticate(username, password) {
if (username === "abishek" && password === "password") {
sessionStorage.setItem('username', username)
return true;
} else {
return false;
}
}
public isUserLoggedIn() {
let user = sessionStorage.getItem('username')
return !(user === null)
}
public logOut() {
sessionStorage.removeItem('username')
}
}
In LoginComponent.ts while click on login button which call checkLogin()
function
checkLogin() {
if (this.loginservice.authenticate(this.username, this.password)
) {
this.router.navigate([''])
} else
// some error
}
My routing config remains same
Upvotes: 1