简体   繁体   中英

One router with Multiple components in Angular

I have two components which are DashboardComponent and LoginComponent. when user hits my website url ie 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 ie 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}
];

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM