根据ngIf条件在Angular中更改NavBar的内容

时间:2019-06-19 04:47:55

标签: node.js angular web-applications node-modules

我是Angular和Node JS的初学者。我正在尝试基于ngIf条件的简单导航栏更改。但是,它似乎不起作用。

我已经使用静态成员变量进行了尝试。

此外,尝试创建一种方法来更改isUserAuthenticatednavbar.component的值,并调用homepage.componentdashboard.component中的方法。

我还完成了console.log()并检查了isUserAuthenticated变量的值。它在homepage.componentdashboard.component上都正在更新。但是,导航栏始终保持不变。

我直接在navbar.component中更改了值,然后它可以工作。因此,我在徘徊为什么我更改其他组件的值后它不起作用。

navbar.component.html

       <div *ngIf="!isUserAuthenticated">
          <li class="nav-item">
            <a class="nav-link" href="/"> EX FALSE </a>
          </li>
        </div>

        <div *ngIf="isUserAuthenticated">
          <li class="nav-item">
            <a class="nav-link" href="/"> EX TRUE </a>
          </li>
        </div>

navbar.component.ts

import { Component, OnInit } from '@angular/core';

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

  isUserAuthenticated = true;

  constructor() { }

  ngOnInit() { }

  public authenticate() {
    this.isUserAuthenticated = false;
    return  this.isUserAuthenticated;
  }
  public deauthenticate() {
    this.isUserAuthenticated = true;
    return  this.isUserAuthenticated;
  }
}

homepage.component.ts

import { Component, OnInit } from '@angular/core';
import { NavbarComponent } from '../navbar/navbar.component';


@Component({
  selector: 'app-homepage',
  templateUrl: './homepage.component.html',
  styleUrls: ['./homepage.component.css']
})
export class HomepageComponent implements OnInit {

  constructor( ) {

  }

  ngOnInit() {

    console.log("here");
    this.deauthenticate();


  }

  public deauthenticate()
  {
    const comp2 = new NavbarComponent();
    comp2.deauthenticate();
    console.log(comp2.deauthenticate());
  }
}

dashboard.component.ts

import { Component, OnInit } from '@angular/core';
import { NavbarComponent } from '../navbar/navbar.component';



@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {

  constructor( ) {
  }

  ngOnInit() {

    this.authenticate();
  }

  public authenticate()
  {
    const comp2 = new NavbarComponent();
    comp2.authenticate();
    console.log(comp2.authenticate());
  }

}

我希望dashboard组件在NavBar中显示“ EX TRUE”,而homepage组件在NavBar中显示“ EX FALSE”。

2 个答案:

答案 0 :(得分:1)

这不是设计事物的方式。对于这种情况,您需要创建一个Service,例如AuthService,它将在两个组件之间共享。

AuthEventSvc

export class AuthEventSvc{

   private authEvent = new BehaviorSubject<boolean>(true);
   constructor(){}

   emitAuthStatus(state: boolean){
     this.authEvent.next(state);
   }

   authListener(){
     return this.authEvent.asObservable();
   }

}

然后从 HomeComponent

发出
export class HomepageComponent implements OnInit {

  constructor(private authEvent: AuthEventSvc ) {

  }

  ngOnInit() {
    this.authEvent.emitAuthStatus(false);
  }
}

并在 NavBarComponent

中进行订阅
export class NavbarComponent implements OnInit {

  isUserAuthenticated = true;
  authSubscription : Subscription;

  constructor(private authEvent: AuthEventSvc) { }

  ngOnInit() { 
    this.authSubscription = this.authEvent.authListener().subscribe(state => {
      this.isUserAuthenticated = state;
    })
  }

  ngOnDestroy(){
    this.authSubscription.unsubscribe(); // make sure to unsubscribe
  }

}

您还应该阅读有关how change detection works的信息以及Angular中NgZone的用法,以使它们更加清晰,因为这些主题需要较长的文章进行解释。我只是给您一些面包屑,以帮助您更好地理解:)

答案 1 :(得分:1)

如评论中所述,您需要创建身份验证服务check this for full example

@Injectable()
export class AuthenticationService {
  authenticated$: BehaviorSubject<boolean> = new BehaviorSubject(false);

  public authenticate() {
    this.authenticated$.next(true);
  }

  public deauthenticate() {
    this.authenticated$.next(false);
  }
}

您以这种方式注入它以便能够在模板中使用

import { Component } from '@angular/core';

import { AuthenticationService } from '../authentication/authentication.service';

@Component({
  selector: 'my-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: [ './navbar.component.css' ]
})
export class NavbarComponent {
  constructor(
    public authenticationService: AuthenticationService,
  ) {
  }
}

然后在模板中可以执行此操作

Authenticated {{ authenticationService.authenticated$ | async }}

<div *ngIf="(authenticationService.authenticated$ | async) === true">
  <li class="nav-item">
    <a class="nav-link" href="/">EX TRUE</a>
  </li>
</div>

<div *ngIf="(authenticationService.authenticated$ | async) === false">
  <li class="nav-item">
    <a class="nav-link" href="/">EX FALSE</a>
  </li>
</div>

<button (click)="authenticationService.authenticate()">Authenticate</button>
<button (click)="authenticationService.deauthenticate()">Deauthenticate</button>

尽管我建议在这种情况下使用ngSwitch:

<div>
  <li class="nav-item" [ngSwitch]="authenticationService.authenticated$ | async">
    <a class="nav-link" href="/" *ngSwitchCase="true">EX TRUE</a>
    <a class="nav-link" href="/" *ngSwitchDefault>EX FALSE</a>
  </li>
</div>

此外,如果您希望网站的某些部分具有独立的状态,则可以这样操作:

@Component({
  selector: 'my-homepage',
  templateUrl: './homepage.component.html',
  styleUrls: [ './homepage.component.css' ],
  // this way you have a separate instance of AuthenticationService here anything that will use this service and is rendered under this component will use a localized version of this service
  providers: [AuthenticationService],
})
export class HomepageComponent {
  constructor(
    public authenticationService: AuthenticationService,
  ) {
  }
}