简体   繁体   English

Angular 中具有多个组件的一个路由器

[英]One router with Multiple components in Angular

I have two components which are DashboardComponent and LoginComponent.我有两个组件,它们是 DashboardComponent 和 LoginComponent。 when user hits my website url ie http://localhost:4200 I have to render LoginComponent if user hasn't logedIn already.当用户访问我的网站 url 即 http://localhost:4200 如果用户尚未登录,我必须呈现 LoginComponent。 If user has logged in already, I have to render Dashboard component in the same route ie http://localhost:4200如果用户已经登录,我必须在同一路径中呈现仪表板组件,即 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.但我必须根据登录条件在同一路线中切换组件,就像 facebook,instagram 一样。 how to achieve this in angular?如何在 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在 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在 LoginComponent.ts 中单击调用checkLogin()的登录按钮 function

checkLogin() {
    if (this.loginservice.authenticate(this.username, this.password)
    ) {
      this.router.navigate([''])
    } else
      // some error
  }

My routing config remains same我的路由配置保持不变

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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