How to put the time spent that a person takes on my page? What should go in html? Should it go in component? In angular 2

I try to put the time spent that a person takes on my page through a service, but I have not had success I would appreciate much of your help

What should go in html?

Should it go in component?

This is my code so far

This is service

import {
  Injectable
} from '@angular/core';

@Injectable()
export class TiempoService {


  horas: number = 0;
  minutos: number = 0;
  segundos: number = 0;

  constructor() {}

  tiempoTranscurrido() {
    setInterval(
      () => {
        this.segundos++;
        if (this.segundos == 60) {
          this.minutos++;
          this.segundos = 0;
          if (this.minutos == 60) {
            this.minutos = 0;
            this.horas++;
          }
        }
      }, 1000);
  }
}

This is component

import {
  Component,
  OnInit,
  Input
} from '@angular/core';


import {
  TiempoService
} from "../../servicios/tiempo.service";

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.css']
})
export class MenuComponent implements OnInit {

  private id: number;
  constructor(private tiempoService: TiempoService) {}

  ngOnInit() {

  }

  tiempoTranscurrido() {
    this.tiempoService.tiempoTranscurrido()


  }

}

This is html

<div class="row">
  <div class="small-12 columns">
    <div class="row">
      <div class="small-12 medium-6 columns">
        <span>Tiempo transcurrido</span>
        <h5>{{horas}}:{{minutos}}:{{segundos}}</h5>
      </div>
    </div>
  </div>
</div>

Upvotes: 1

Views: 112

Answers (1)

Denys Reshetniak
Denys Reshetniak

Reputation: 382

You can leverage date pipe from angular

@Component({
  selector: 'my-app',
  template: `
    <div>
      <p>Current time is: {{currentTime | date:'mediumTime'}}</p>
      <p>Time spent on the page: {{timeOnThePage | date:'HH:mm:ss'}}</p>
      <p>I need "start" property in the component because of this
         behaviour {{ 00 | date:'h:m:s'}}</p>
      <p> Zero in date pipe becomes 1:00:00</p>
    </div>
  `,
})
export class App implements OnInit{
  start: number = 82800000;
  timeOnThePage: number;
  currentTime: number = 0;
  now: Date;

  ngOnInit() {
    this.now = new Date().getTime();
    Rx.Observable.interval(1000).subscribe(seconds => {
      this.currentTime = this.now + seconds * 1000;
      this.timeOnThePage = this.start + seconds * 1000;
    })
  }
}

Please, have a look on the plunker demo

Upvotes: 1

Related Questions