角度:变化检测

时间:2021-03-04 10:19:33

标签: angular typescript

我正在开发一个应用程序,我在导航栏上定义了许多选项卡。其中一些是隐藏的。我有一个登录选项卡,在用户登录后,我想让它消失并显示注销选项卡。我已经正确地制定了我的逻辑,但是,我遇到了问题。所有这些选项卡都是路由,而导航栏组件不是。它只在我启动应用程序时呈现一次。我在我的登录组件中使用了服务并将该数据传递给我的导航栏组件,但是,尽管在用户登录后,导航栏不会自行更新新选项卡(注销)。我不得不说点击一个按钮再次调用导航栏组件的 ngOnInit() 方法。这是我的代码:

<块引用>

navbar.component.html

<div class="collapse navbar-collapse" id="navbarSupportedContent" >
<ul class="navbar-nav ml-auto">
  <li class="nav-item" routerLinkActive = "active" [routerLinkActiveOptions] = "{exact: true}">
    <a class="nav-link" routerLink = "/">Home</a>
  </li>
  <li class="nav-item" routerLinkActive = "active">
    <a class="nav-link" routerLink = "/findcourse">Find Courses</a>
  </li>
  <li class="nav-item" routerLinkActive = "active">
    <a class="nav-link" routerLink = "/feedback">Feedback</a>
  </li>
  <li class="nav-item" routerLinkActive = "active">
    <a class="nav-link" routerLink = "/register">Register</a>
  </li>
  <li class="nav-item" routerLinkActive = "active" *ngIf = "loggedIn">
    <a class="nav-link" routerLink = "/login">Login</a>
  </li>
  <li class="nav-item" routerLinkActive = "active" *ngIf = "loggedOut">
    <a class="nav-link" routerLink = "/logout">Log out</a>
  </li>
  <button type="button" name="button" class = "btn btn-outline-info" (click) = "ngOnInit()">Check</button>
</ul>
</div>
<块引用>

navbar.component.ts

ngOnInit(): void         //I want to call this on its own not only at the time of rendering but every time user logs in
{
if(this.login.isAuthenticated() == true)
{
  this.loggedOut = true;
  this.loggedIn = false;
}
else if(this.login.isAuthenticated() == false)
{
  this.loggedOut = false;
  this.loggedIn = true;
}
}
<块引用>

登录.component.ts

logIn(form: NgForm)
{
 this.http.post('http://localhost:3000/login', form.value, {responseType: "text"})
 .subscribe(responseData => {
  if(responseData == 'Successfully logged in')
  {
    this.logInSuccess = true;
    this.showlogInAlert();
    this.auth.checkAuthentication(true);
  }
  else if(responseData == 'User login failed')
  {
    this.logInFailure = true;
    this.auth.checkAuthentication(false);
  }
 }
,error =>{
this.serverError = true;
this.showserverAlert();
});

form.reset();
}
<块引用>

登录.service.ts

 export class Login
{
 logInSuccess: boolean = false;

 checkAuthentication(check : boolean)
{
 if(check === true)
 {
  this.logInSuccess = true;
 }
 else
 {
  this.logInSuccess = false;
 }
}

isAuthenticated()
{
 return this.logInSuccess;
}
}

如何自行重新渲染导航栏?我不知道该怎么做?有没有办法让 Angular 自己检查导航栏中的变化检测?

1 个答案:

答案 0 :(得分:2)

快速修复方法是直接在您的 html 中使用登录服务 isAuthenticated 值:

const { id } = req.params;

try {
    const post = await PostMessage.findById({id: id});
    res.status(200).json(post);
} catch (error) {
  res.status(404).json({ message: error.message });
}

它将在更新时从服务中获取最新值。

在更改检测方面更有效的是将值公开为可观察对象并订阅组件中的更改。 this question 的示例。