Angular2防止在路由更改时销毁Component

时间:2016-12-13 18:35:19

标签: javascript angular components

我使用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;

    }
}

2 个答案:

答案 0 :(得分:4)

您应该使用@Injectable使用服务,然后您将能够导航不同的路线,并且仍然可以使用秒表计数。

这是一个有关的例子: https://embed.plnkr.co/mKThXNaMIlBUMlkXwjr5/

答案 1 :(得分:0)

为什么不将Component放在其中一个父组件中,只是在应用程序处于所需状态时隐藏或显示它。(无需为其指定特殊路径)。