代码之家  ›  专栏  ›  技术社区  ›  woodykiddy

多个组件间的角度计时器可观察和重用订阅

  •  0
  • woodykiddy  · 技术社区  · 7 年前

    当我呆在家里的时候,重新定向是正确的 component 1 让时间在50分钟后结束。但是如果我在的话,我就不会被重定向 component 2 因为某种原因。计时器仍然继续计数,直到达到限制,但就是不允许重定向。

    下面是我迄今为止尝试的代码。

    @Injectable()
    export class TimerService {
        private readonly interval = 1000;
        private _timer$: Observable<number>;
        private _sub$: Subscription;
    
        constructor() {
            this._timer$ = timer(0, this.interval);
        }
    
        public get timer(): Observable<number> {
            return this._timer$;
        }
    
        public subscribe(fnExp: any): Subscription {
            if (!this._sub$) {
                this._sub$ = this._timer$.subscribe(fnExp);
            }
            return this._sub$;
        }
    
        public unsubscribe() {
            if (this._sub$) {
                this._sub$.unsubscribe();
            }
        }
    }
    

    ngOnInit() {
        const timerSub$ = this._timerService.subscribe(x => {
          console.log(x);
          this.count = x;
          if (x === 50) {
            this._timerService.unsubscribe();
            console.log('stopped');
            this._router.navigate(['../'], {relativeTo: this._route});
          }
        });
      }
    

    this._router.navigate(['../'], {relativeTo: this._route})

    0 回复  |  直到 7 年前