我如何将sec转换为hh:mm:ss格式的angular2

时间:2018-01-24 05:40:58

标签: angular typescript angular2-observables

我试过这个

剩余时间= {{counter}}


但它只是以第二种格式显示我。 我想要的是......:mm:ss格式。 我想在测验计时器中实现他的功能,其中计时器减少。 在我的.ts文件中,我使用var计数器并使用角度OBSERVABLE方法使用.map方法递减。

我想减少计时器以结束测验。例如:1:20:60到0:0:0。当计时器结束时,我想提交测验。

startTimer所(){

this.countDown = Observable.timer(0,1000)
.take(this.counter)
.map( x=> --this.counter)
.subscribe(x=>this.timer(x))

}

3 个答案:

答案 0 :(得分:1)

我自己实现了这段代码

var callDuration = this.elementRef.nativeElement.querySelector('#time');
this.startTimer(callDuration);

startTimer(display){
var timer = 3600;
var minutes;
var seconds;
var hours;
this.display1=display;

  this.sub = Observable.interval(1000).subscribe(x => {
  hours = Math.floor(timer / 3600)
  minutes = Math.floor((timer % 3600)/60);
  seconds = Math.floor(timer % 60);

  hours = minutes < 10 ? "0" + hours : hours;
  minutes = minutes < 10 ? "0" + minutes : minutes;
  seconds = seconds < 10 ? "0" + seconds : seconds;

  display.textContent = hours + ":" + minutes + ":" + seconds;

  --timer;
  if (timer < -1) {
    this.sub.unsubscribe();
    display.textContent ="00:00:00";
    window.alert("Times Up, Quiz Submitted");

答案 1 :(得分:0)

你好,这是一个建议。

import {Component, Directive, Output, OnInit, EventEmitter, Input, SimpleChange} from '@angular/core'
    import {Observable} from 'rxjs/Observable';
    import {Observer} from 'rxjs/Observer';
    import 'rxjs/Rx';


    @Component({
      selector: 'my-app',
      template: `
      {{ timeMask(tick) }}
      `
    })
    export class App implements OnInit {

      private tick: number = 72;
      private myobs = Observable.timer(1000,1000).map( m =>  m );

      ngOnInit(){
        this.myobs.subscribe( x => if( this.tick > 0){ this.tick-- } );
      }

      timeMask(value: number): string {
           const minutes: number = Math.floor(value / 60);
           return minutes + ':' + (value - minutes * 60);
       }

    }

link for the plunker

答案 2 :(得分:0)

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/interval';
import 'rxjs/add/operator/takeWhile';

@Component({
  selector: 'app-root',
  template: `
  {{miliseconds |date:'HH:mm:ss':'+0000'}} 
  `
})
export class AppComponent implements OnInit {
  miliseconds:number
  alive:boolean=true;
  ngOnInit()
  {
    this.miliseconds=5000;
    Observable.interval(1000)
        .takeWhile(()=>this.alive)
        .subscribe(x => {
             this.miliseconds-=1000;
             if (this.miliseconds<0)
             {
               this.miliseconds=0;
               this.alive=false;
               window.alert("Times Up, Quiz Submitted");
             }
         })
  }
}