2016-12-13 35 views
1

我使用我的angular2应用的angular-seed模板。我写了一个简单的秒表。如果我启动计时器并更改路线,组件将被销毁并且计时器停止。我怎样才能防止这一点?计时器应该在后台工作。Angular2防止在路由更改时销毁组件

import {Component, ElementRef} from "@angular/core"; 
 
import {WindowService} from "../services/window.service"; 
 

 
@Component({ 
 
    selector: 'timer', 
 
    template: `<div> 
 
       <span>0</span><br> 
 
       <button (click)="start()">start</button> 
 
       <button (click)="stop()">stop</button> 
 
       </div>` 
 
}) 
 

 
export class TimerDirective { 
 

 
    private running:boolean; 
 
    private time:number; 
 
    private results:Array<any>; 
 
    private laps:Array<string>; 
 
    private times:Array<number>; 
 
    private win:any; 
 
    private timeEnd:any; 
 

 

 
    constructor(private el: ElementRef, private winA: WindowService) { 
 
     console.log("time"); 
 

 
     this.running = false; 
 
     this.time = -1; 
 
     this.results = []; 
 
     this.laps = []; 
 
     this.times = [0, 0, 0]; 
 
     this.win = window; 
 
     this.timeEnd = performance; 
 

 
    } 
 

 
    ngOnDestroy() { 
 
     this.winA.alert("no please"); 
 
    } 
 
    public reset() { 
 
     this.times = [0,0,0]; 
 
    } 
 

 
    public stop() { 
 
     this.running = false; 
 
     this.time = -1; 
 
    } 
 

 
    public start() { 
 
     if(this.time === -1) { 
 
      this.time = this.timeEnd.now(); 
 
     } 
 
     if(this.running == false) { 
 

 
      this.running = true; 
 
      requestAnimationFrame(this.step.bind(this)); 
 
     } 
 
    } 
 

 
    public step(timestamp:any) { 
 
     if(this.running == false) { 
 
      return; 
 
     } 
 
     this.calculate(timestamp); 
 
     this.time = timestamp; 
 
     this.print(); 
 
     requestAnimationFrame(this.step.bind(this)); 
 
    } 
 

 
    public calculate(timestamp:any) { 
 
     let diff = timestamp - this.time; 
 

 
     this.times[2] += diff/10; 
 

 
     if (this.times[2] >= 100) { 
 
      this.times[1] += 1; 
 
      this.times[2] -= 100; 
 
     } 
 

 
     if (this.times[1] >= 60) { 
 
      this.times[0] += 1; 
 
      this.times[1] -= 60; 
 
     } 
 
    } 
 

 
    public print() { 
 
     let elSpan = this.el.nativeElement.querySelector('span'); 
 
     elSpan.innerHTML = this.times; 
 

 
    } 
 
}

+0

@günter-zöchbauer这不是重复的问题。 – Fiddles

回答

0

你为什么不把你的组件在父组件之一,只是隐藏或显示,如果应用程序是在理想状态(无需指定特殊的路由。为了它)。

相关问题