简体   繁体   English

Angular2防止在路线更改时破坏Component

[英]Angular2 prevent destroying a Component on route change

I use angular-seed template for my angular2 app. 我为angular2应用程序使用了角种子模板。 And I wrote a simple stopwatch. 我写了一个简单的秒表。 If i start the timer and change the route, the component will be destroyed and the timer stops. 如果我启动计时器并更改路线,该组件将被破坏,计时器停止。 How can I prevent this? 我该如何预防? The timer should work in the background. 计时器应在后台运行。

 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; } } 

You should use a service using @Injectable then you will be able to navigate different routes and still have the stopwatch counting. 您应该使用通过@Injectable使用的服务,这样您就可以导航不同的路线,并且仍然可以使秒表计数。

Here is a plunker example: https://embed.plnkr.co/mKThXNaMIlBUMlkXwjr5/ 这是一个小例子: https ://embed.plnkr.co/mKThXNaMIlBUMlkXwjr5/

为什么不将组件放在父组件之一中,而只是将其隐藏或显示(如果该应用处于所需状态)(无需为其指定特殊路由)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM