【问题标题】:Why my view is not updated after page is destroyed and i come back with setInterval?为什么页面被销毁后我的视图没有更新,我返回 setInterval?
【发布时间】:2022-06-10 22:31:28
【问题描述】:

我有两页

应用组件 HTML

<a routerLink="hello-page">HELLO PAGE</a>
<div></div>
<a routerLink="counter">COUNTER</a>
<router-outlet></router-outlet>

计数器 HTML

<p>{{ counter }}</p>
<button (click)="onBtnClick()">Click</button>

计数器 TS

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

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

  ngOnInit() {}

  counter: number = 0;
  onBtnClick() {
    setInterval(() => {
      this.counter++;
      console.log('interval counter', this.counter);
    }, 1000);
  }
}

HELLO-PAGE HTML

<p>
hello-page works!
</p>

当我访问计数器页面并单击按钮时 - 我开始间隔 - 在里面我每隔一秒增加我的 counter property 的值,所以 1 2 3 4 etc。 视图也更新了 - 我们可以在 HTML 中看到 1 2 3 4

在计算时间间隔时 - 我单击 HELLO-PAGE 链接,然后我被路由到 hello 页面组件。 当我进入该页面时,我可以看到间隔仍在计数(我在 ngOnDestroy 中销毁页面时没有清除间隔)并且他仍在滴答作响。

之后,当我再次返回 counter 组件时,间隔仍在工作,计数器正在增加,但 THE VIEW IS NOT UPDATED。 HTML 中的{{ counter }} 现在为 0。

我猜这是因为 previos 视图被破坏了,现在我有了新视图。 我需要找到一种方法,当我返回该页面时,我将从 HTML 中的前一个 setInterval 中获取值。

所以我的 HTML 将被更新。

你可以在这里找到完整的代码

https://stackblitz.com/edit/angular-upmaek?file=src%2Fapp%2Fcounter%2Fcounter.component.ts,src%2Fapp%2Fcounter%2Fcounter.component.css,src%2Fapp%2Fcounter%2Fcounter.component.html,src%2Fapp%2Fapp-routing.module.ts,src%2Fapp%2Fapp.module.ts,src%2Fapp%2Fhello-page%2Fhello-page.component.html

【问题讨论】:

    标签: javascript angular angular2-changedetection


    【解决方案1】:

    你可以停止间隔。

    CounterComponent.ts:

    export class CounterComponent implements OnInit, OnDestroy {
      constructor() {}
      ngOnDestroy(): void {
        clearInterval(this.intervalCount);/////
      }
      ngOnInit() {}
      counter: number = 0;
      intervalCount: any;
      onBtnClick() {
        this.intervalCount = setInterval(() => {
          this.counter++;
          console.log('interval counter', this.counter);
        }, 1000);
      }
    }
    

    【讨论】:

    • 我不想停止我的间隔。我需要继续。
    【解决方案2】:

    您可以将时间间隔移动到服务中,并在CounterComponent 中注入服务并从中获取当前计数器值。

    【讨论】:

      猜你喜欢
      • 2015-08-16
      • 2015-04-24
      • 1970-01-01
      • 2021-11-06
      • 2011-05-17
      • 2014-06-15
      • 1970-01-01
      • 2016-08-09
      • 1970-01-01
      相关资源
      最近更新 更多