【问题标题】:Method being triggered every 10 seconds and run repeatedly in app.component.html file方法每 10 秒触发一次并在 app.component.html 文件中重复运行
【发布时间】:2020-06-26 12:02:49
【问题描述】:

我有一个 Angular 9 应用程序(最近从 7 升级,但在 7 中仍然有同样的问题),在我的 app.component.html 文件中我有下面的代码。 页面加载正确,一切看起来都很好。 但是方法

getSideBarState() // 返回一个布尔值

在我第一次启动调试器时,'toggled' 和 'show' ngClass 都会被触发并运行至少 10 次以上。然后在最后一个运行后,它等待约 10 秒,然后再次触发约 10 秒并运行。并且这会不断地被触发和运行。

谁能告诉我为什么,以及如何阻止它被触发并运行这么多次?我只希望它在应用首次加载时运行一次。

<div class="page-wrapper" [ngClass]="{'toggled' : getSideBarState()}" (window:resize)="onResize()">
  <app-sidebar></app-sidebar>
  <main class="page-content">
    <div class="">
      <app-nav-bar></app-nav-bar>
      <router-outlet (activate)="onActivate($event)"></router-outlet>
    </div>
    <div class="overlay" (click)="toggleSidebar()" [ngClass]="{'show' : !getSideBarState()}"></div>
  </main>
</div>

【问题讨论】:

    标签: javascript angular typescript ng-class


    【解决方案1】:

    这是按照 Angular 的设计工作的。

    getSideBarState 将在每次更改检测在 Angular 应用程序中运行时被调用,几乎在每个生命周期钩子上以及更多次(我目前不知道),因为你正在使用函数(它返回一些东西到模板)在模板中而不是简单的变量绑定。

    你如何避免这种情况?

    为了避免在ngOnInit 或其他合适的生命周期钩子中调用你的函数getSideBarState 并将返回值分配给一个变量,然后在模板中绑定到该变量,这样它就不会运行多个次。

    例如-

    ngOnInit() {
        getSideBarState();
    }
    getSideBarState() {
        ... Some calculations (here `classState` is variable)
        classState = true/false;    // return value
    }
    
    <div class="page-wrapper" [ngClass]="{'toggled' : classState}" (window:resize)="onResize()">
      <app-sidebar></app-sidebar>
      <main class="page-content">
        <div class="">
          <app-nav-bar></app-nav-bar>
          <router-outlet (activate)="onActivate($event)"></router-outlet>
        </div>
        <div class="overlay" (click)="toggleSidebar()" [ngClass]="{'show' :!classState}"></div>
      </main>
    </div>
    

    希望这个答案对你有所帮助。

    【讨论】:

    • 谢谢!这是有道理的……对 Angular 来说还是有点新意
    • 很高兴知道,我的内容帮助了你 :) 继续摇摆!
    猜你喜欢
    • 1970-01-01
    • 2018-11-08
    • 2016-04-16
    • 1970-01-01
    • 2019-11-07
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    相关资源
    最近更新 更多