角度,当导航到另一个页面时,出现不确定的错误

时间:2020-10-22 06:12:42

标签: angular slick.js

我在首页/home上有2个光滑的轮播机

slider.component.ts

  @ViewChild('mainBannerModal') mainBannerModal: SlickCarouselComponent;
  @ViewChild('eventsModal') eventsModal: SlickCarouselComponent;

  next(modal) {
   if (modal) {
    modal.slickNext(); // when navigate to another page gives an error , even with condiition if modal
   }
  }

  startProgressbar() {
    this.resetProgressbar();
    this.percentTime = 0;
    this.tick = setInterval(this.interval.bind(this), 10);
  }

  interval() {
    this.percentTime += 1 / (this.time + 0.1);
    this.progressBarWidth = this.percentTime;
    if (this.percentTime >= 100) {
      this.next(this.mainBannerModal); // HERE I pass my exact slick modal and invoke function
      this.startProgressbar();
    }
  }

  resetProgressbar() {
    this.progressBarWidth = 0;
    clearTimeout(this.tick);
  }

slider.component.html

<div *ngIf="mainSlider">
     <ngx-slick-carousel class="carousel" #mainBannerModal="slick-carousel" [config]="slideConfig">
       ... carousel 1
    </ngx-slick-carousel>
</div>
<div *ngIf="eventsSlider">    
    <ngx-slick-carousel class="carousel" #eventsModal="slick-carousel" [config]="slideConfig">
       ... carousel 2
    </ngx-slick-carousel>
</div>

当我从/home页(光滑的轮播)导航到另一页猜测/registration时,我有 infinitive 错误日志

错误TypeError:无法读取未定义的属性'slick'

请帮助

UPD 1

仅供参考,我以此方式将幻灯片导入首页

main-page.component.html

<section class="main">
  <app-slider mainSlider="true"></app-slider>
  <app-slider eventsSlider="true"></app-slider>
</section>

1 个答案:

答案 0 :(得分:1)

您的代码段似乎缺少一些重要的部分,因此只能猜测...

  1. 您正在呼叫setInterval,但使用clearTimeout将其清除。 您应该改用clearInterval

clearTimeoutsetTimeout一起使用。

  1. 您设置的时间间隔可能保持活动状态,当您的组件已被路由器销毁时,将导致调用某些东西。

尝试实现OnDestroy,然后在ngOnDestroy内调用您的reset方法:

import { OnDestroy } from '@angular/core';

@Component(...)
export class YourComponent implements OnDestroy
{
   ...

   private clearInterval(): void
   {
      if (this.tick)
      {
          clearInterval(this.tick);
          this.tick = null;
      }
   }

   ngOnDestroy()
   {
       this.clearInterval();
   }
}

当用户导航到新路线时,路由器将破坏您的组件并致电ngOnDestroy,以确保间隔被清除。