单击更改按钮图标

时间:2020-05-17 12:08:25

标签: angular

我正在尝试在登录/注销时更改图标和按钮的功能。我编写了以下代码:

navbar.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthenticationService } from 'src/app/services/authentication.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.scss']
})
export class NavbarComponent implements OnInit {
  public loggedIn; 

  constructor(private authService : AuthenticationService, private router : Router) { 
    this.loggedIn = this.authService.isLoggedIn(); 
  }

  ngOnInit(): void {
  }

  logOut(){
    this.authService.logout() 
    this.router.navigate(['/login']);
  }
}

navbar.component.html

<mat-toolbar color="primary">
    <mat-toolbar-row>
        <span>SB Betting</span>

        <span class="example-spacer"></span>
        <button *ngIf="!loggedIn" mat-icon-button [routerLink]="'/login'">
            <mat-icon class="example-icon" aria-hidden="false" aria-label="Login">exit_to_app</mat-icon>
        </button>
        <button *ngIf="loggedIn" mat-icon-button [routerLink]="'/'" (click)="logOut()">
            <mat-icon class="example-icon" aria-hidden="false" aria-label="Logout">settings_power</mat-icon>
        </button>
    </mat-toolbar-row>
</mat-toolbar>

在导航栏中单击按钮之一后,图标/功能不会更改,单击时用户将登录/注销,并且刷新后将加载正确的图标。如何在不重新加载页面的情况下实现此目的?我还尝试将this.loggedIn = this.authService.isLoggedIn();放在ngInit方法中。

1 个答案:

答案 0 :(得分:1)

注销后单击时,您必须重新分配变量。这将更改您的按钮。

version: '2'

services:

  redis:
    image: redis
    ports:
      - "6385-6387:6379"
    volumes:
      - /host_mnt/d/redis_scale:/data
    restart: always

对于从LoginComponent更新导航,您需要进行组件交互。您需要在这两个组件中注入一项服务。

this.loggedIn = this.authService.isLoggedIn(); 

现在,您需要从“登录”组件中进行以下操作。

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CommonServiceService {

  private loginDone= new BehaviorSubject<boolean>();
  loginDoneObservable$ = this.loginDone.asObservable(); 

  constructor() { }

  loginDone(status){
    this.loginDone.next(status);
  }
}

在NavigationComponent中,您需要订阅可观察的服务。

this._commonServices.loginDone(true);