【发布时间】:2019-11-01 18:05:04
【问题描述】:
我是 Angular 和 Node JS 的初学者。我正在尝试根据 ngIf 条件更改简单的导航栏。但是,它似乎不起作用。
我已经尝试过使用静态成员变量。
另外,尝试创建一个方法来更改navbar.component 中isUserAuthenticated 的值,并调用homepage.component 和dashboard.component 中的方法。
我也完成了console.log() 并检查了isUserAuthenticated 变量的值。它正在homepage.component 和dashboard.component 上进行更新。但是,NavBar 始终保持不变。
我已经直接在 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 组件在导航栏中显示“EX TRUE”,而homepage 组件在导航栏中显示“EX FALSE”。
【问题讨论】:
-
您应该使用一些服务来管理您的身份验证状态并创建不属于渲染视图的新组件,这就是您的方法调用不做任何事情的原因
-
这个问题现在看起来不一样了,您是想为身份验证设置全局状态,还是只为每个显示位置设置本地状态?
-
感谢您的回答。它现在正在工作。我赞成您的回答并标记为正确。再次感谢您。
标签: node.js angular web-applications node-modules