如何以角度4注销后禁用按钮?

时间:2017-12-14 12:36:14

标签: angular typescript

我有一个父应用程序组件,其中包含一个水平菜单,其中包含不同的按钮。每个按钮都会在菜单下显示子组件。当登录登录按钮变为注销时。当我按下注销时,它应该再次从DOM中取出所有按钮。我无法实现这一点。它在我使用时有用,

changeDetection: ChangeDetectionStrategy.OnPush

表示AppComponent类。然而,这具有阻止子组件中的任何列表的令人不快的副作用  从渲染中检索数据库。此外,我必须使用代码location.reload()重新加载应用程序,以便按钮再次消失。

当我不使用OnPush策略时,我收到错误

 "ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'."

任何人都可以告诉我应该改变什么以使其正常工作吗?

我使用服务来使不同的组件相互通信。 以下是我的代码:

应用程序组件

@Component({
  //changeDetection: ChangeDetectionStrategy.OnPush,
  selector:'app-root',
  templateUrl:'./app.component.html',
  styleUrls:['./app.component.css']
})
export class AppComponent {
  title: string;
  isEnabledForUser: boolean = false;
  isEnabledForAdmin: boolean = false;

  //private ref: ChangeDetectorRef
  //      this.ref.detectChanges()

  constructor(private loginService: LoginService) {
    this.title = "Verlofurenregistratie";
    loginService.loginSuccessful$.subscribe(val =>{
      console.log("received an new value")
      this.isEnabledForUser = val
      this.isEnabledForAdmin = false})
    loginService.adminLoginSuccessful$.subscribe(val =>{
      console.log("received an new value")
      this.isEnabledForAdmin = val;
      this.isEnabledForUser = val;
    })
    loginService.logout$.subscribe(val => {
      this.isEnabledForAdmin = val;
      this.isEnabledForUser = val;
    })
  }
}

appcomponent HTML

<header class="page-header">
  <h1>{{title}}</h1>
  <nav>
    <ul class="nav nav-pills">
      <li role="presentation" [routerLinkActive]="['active']">
        <a [routerLink]="['/login']">{{!(isEnabledForAdmin || isEnabledForUser) ? "Login" : "Logout"}}</a>
      </li>
      <li *ngIf="isEnabledForAdmin" role="presentation" [routerLinkActive]="['active']">
        <a [routerLink]="['/account/create']">Account aanmaken</a>
      </li>
      <li *ngIf="isEnabledForAdmin" role="presentation" [routerLinkActive]="['active']">
        <a [routerLink]="['/account/list']">Account overzicht</a>
      </li>
      <li *ngIf="isEnabledForUser" role="presentation" [routerLinkActive]="['active']">
        <a [routerLink]="['/leave/create']">Verlofuren aanvragen</a>
      </li>
      <li *ngIf="isEnabledForAdmin" role="presentation" [routerLinkActive]="['active']">
        <a [routerLink]="['/leave/list']">Verlofuren overzicht</a>
      </li>
      <li *ngIf="isEnabledForAdmin" role="presentation" [routerLinkActive]="['active']">
        <a [routerLink]="['/leave/pending']">Verlofaanvragen overzicht</a>
      </li>
    </ul>
  </nav>
</header>
<div class="alert alert-info" role="alert">Berichten&hellip;</div>
<router-outlet></router-outlet>

登录子组件

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers: [AccountService]
})
export class LoginComponent implements OnInit, OnChanges {
  title: string;
  loggedIn: boolean = false;
  loginForm: FormGroup;
  loading = false;
  error = '';
  constructor(private fb: FormBuilder,
              private accountService: AccountService,
              private router: Router,
              private loginService: LoginService,
              private ref: ChangeDetectorRef) {
    this.title = "Inloggen";
    this.loginForm = fb.group({
      email: ['', [Validators.required, Validators.email]],
      password: ['', Validators.required]
    });
  }

  ngOnInit(): void{
    console.log("I'm in ngOnChanges right now..")
    if(localStorage.getItem("account") !== null){
      console.log("loggedIn is true")
      localStorage.clear()
      // this.ref.detectChanges()
      //this.loginService.onLogout()
       this.loginService.isLoginSuccessful(false, "user");
      //location.reload(false)
    }
  }

  ngOnChanges(): void {

  }

  onSubmit() {
    const formModel = this.loginForm.value;
    this.accountService.authenticate(formModel.email, formModel.password).then(account =>
    {
        if (account !== undefined && account.enabled) {
          localStorage.setItem("account",JSON.stringify(account))
          this.loggedIn = true;
      if(account.admin) {
        this.loginService.isLoginSuccessful(true, "admin");
        this.router.navigate(["leave/pending"])
      }
      else {
        this.loginService.isLoginSuccessful(true, "user");
        this.router.navigate(["leave/create"])
      }
      }
    });
  }
}

登录HTML

<h2>{{title}}</h2>
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
  <div class="form-group">
    <label for="email">E-mailadres</label>
    <input type="email" id="email" class="form-control"
           placeholder="naam@mail.com"
           formControlName="email">
  </div>
  <div class="form-group">
    <label for="password">Wachtwoord</label>
    <input type="password" id="password" class="form-control"
           formControlName="password">
  </div>
  <div class="form-group">
    <button type="submit" class="btn btn-default">Inloggen</button>
  </div>
</form>

谢谢

1 个答案:

答案 0 :(得分:-1)

在appComponent.html中,您可以执行以下操作:

<header class="page-header">
  <h1>{{title}}</h1>
  <nav>
    <ul class="nav nav-pills">
      <li role="presentation" [routerLinkActive]="['active']">
        <a *ngIf="!(isEnabledForAdmin || isEnabledForUser)" [routerLink]="['/login']">Login</a>
        <a *ngIf="isEnabledForAdmin || isEnabledForUser" [routerLink]="['/login']">Logout</a>
      </li>
      <li *ngIf="isEnabledForAdmin" role="presentation" [routerLinkActive]="['active']">
        <a [routerLink]="['/account/create']">Account aanmaken</a>
      </li>
      <li *ngIf="isEnabledForAdmin" role="presentation" [routerLinkActive]="['active']">
        <a [routerLink]="['/account/list']">Account overzicht</a>
      </li>
      <li *ngIf="isEnabledForUser" role="presentation" [routerLinkActive]="['active']">
        <a [routerLink]="['/leave/create']">Verlofuren aanvragen</a>
      </li>
      <li *ngIf="isEnabledForAdmin" role="presentation" [routerLinkActive]="['active']">
        <a [routerLink]="['/leave/list']">Verlofuren overzicht</a>
      </li>
      <li *ngIf="isEnabledForAdmin" role="presentation" [routerLinkActive]="['active']">
        <a [routerLink]="['/leave/pending']">Verlofaanvragen overzicht</a>
      </li>
    </ul>
  </nav>
</header>
<div class="alert alert-info" role="alert">Berichten&hellip;</div>
<router-outlet></router-outlet>