Что я пытаюсь сделать:
генерируется случайное число
таймер считает это число и затем показывает кнопкусо случайным полем
первый таймер останавливается, второй таймер запускается
, когда пользователь нажимает кнопку, сколько времени второй таймер печатаетпрошло между появлением кнопки и щелчком
Я хотел создать поле класса компонента, которое является логическим, и при нажатии кнопки логическое значение меняется на true, а затем таймер при каждомtick проверяет логическое значение и, если true, удаляет кнопку и снова запускает первый таймер.
Проблема в том, что при нажатии кнопки поле, по которому щелкнули, не изменяется.В чем тут подвох?
import { Component, OnInit } from '@angular/core';
import {TimerObservable} from "rxjs/observable/TimerObservable";
@Component({
selector: 'app-gra',
templateUrl: './gra.component.html',
styleUrls: ['./gra.component.css']
})
export class GraComponent implements OnInit {
randNum: any;
timerSub: any;
userTimerSub: any;
clicked: boolean;
constructor() { }
ngOnInit() {
this.randNum = 3+ Math.floor(Math.random()*3);
console.log('random: ' + this.randNum)
this.clicked = false;
let timer = TimerObservable.create(0, 1000);
this.timerSub = timer.subscribe( d => this.timerFunction(d) );
}
timerFunction(d){
console.log(d);
if(d === this.randNum){
var btn = document.createElement("BUTTON"); // Create a <button> element
var t = document.createTextNode("CLICK ME"); // Create a text node
btn.appendChild(t);
btn.id = "button"
let margin = Math.floor(Math.random()*500);
document.body.appendChild(btn); // Append <button> to <body>
btn.setAttribute('style', 'margin-top: ' + margin + "px;");
document.getElementById("button").addEventListener("click", this.buttonClick);
this.timerSub.unsubscribe();
let timer = TimerObservable.create(0, 1000);
this.userTimerSub = timer.subscribe( d => this.userTimerFunction(d) );
this.randNum = 3 + Math.floor(Math.random()*3);
console.log('new rand: ' + this.randNum)
}
}
userTimerFunction(d){
console.log('user' + d)
console.log(this.clicked)
if(this.clicked == true){
console.log('It took you ' + d + 'seconds');
this.userTimerSub.unsubscribe();
var element = document. getElementById("button");
element.parentNode.removeChild(element);
let timer = TimerObservable.create(0, 1000);
this.timerSub = timer.subscribe( d => this.timerFunction(d) );
}
}
buttonClick(){
console.log('clicked: ' + this.clicked);
this.clicked = true;
}
}