Angular5- setInterval使页面变白

时间:2018-04-18 10:33:05

标签: angular5 setinterval

我正在为我的项目添加通知。该网站应显示用户在没有刷新页面的情况下获得的许多通知编号。为此,我在setInterval中使用了ngOnInit函数,但是当我在ngOnInit中使用它时,页面变白并且只显示计时器仍在运行。 这是我如何实现代码。 的 ngOnInit

    ngOnInit() {
    this.subscription = this.loginInfoService.getLoginChangeEmitter()
      .subscribe(item => this.loginSuccess(item));

    this.subscription = this.loginInfoService.getSiteNameEmitter()
      .subscribe(item => this.getSiteName(item));

    this.subscription = this.loginInfoService.getSiteDescriptionEmitter()
      .subscribe(item => this.getSiteDescription(item));

    if (innerWidth < 766) {
      this.notificationBell = true;
    } else {
      this.notificationBell = false;
    }

    //if i add this line page goes white
    setInterval(() => {
      this.getAllNotification();
    }, 3000);

  }

获取所有通知的代码

getAllNotification() {

        this.unSeenNotification = [];
        this.notificationService.getAllNotifications().subscribe(
          result => {
            this.notificationModel = result;
            this.showLoading = false;

            result.forEach(result => {
              if (!result.isSeen) {
                this.unSeenNotification.push(result);
              }
            })

            this.notificationCount = this.unSeenNotification.length;

          },
          error => {
            this.alertService.error(error, "Error!");
          });
  }

1 个答案:

答案 0 :(得分:1)

您可以低于窗口间隔:

export class FoobarComponent implements OnInit {

static intervalId: Number;

ngOnInit(): void {
    this.startInterval();
}

startInterval() void {
    if(FoobarComponent.intervalId) { // always undefined 
        window.clearInterval(this.intervalId);
    }
    FoobarComponent.intervalId = window.setInterval(() => { 
        console.log('Hi'); }, 1000);
      }
 }